html - 我使用角度模板驱动的形式创建简单的形式
问题描述
但我得到了这个错误,
对象可能为 'null <span *ngIf="name.errors.minlength">您必须输入至少 3 个字符
为什么我的错误对象始终为空,minlength 未存储在我的错误对象中这是什么原因?
我的 hero.ts 文件是,
export class Hero {
constructor(
public id: number,
public name: string,
public email: string
) { }
}
我的 formone.component.ts 文件是,
import { Component, OnInit } from '@angular/core';
import {NgForm} from "@angular/forms";
import {Hero} from "../../hero"
@Component({
selector: 'app-formone',
templateUrl: './formone.component.html',
styleUrls: ['./formone.component.css']
})
export class FormoneComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
model = new Hero(1, 'chamara','chamara@gmail.com');
submitted = false;
onSubmit() { this.submitted = true; }
get diagnostic() { return JSON.stringify(this.model); }
}
我的 formone.component.html 文件是,
<div class="container mt-3">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8">
<h4>Template Driven Forms</h4>
<form #formone="ngForm" (ngSubmit)="onSubmit()">
{{diagnostic}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name" #name="ngModel" minlength="3" #x>
</div>
<div *ngIf="!name.valid" class="alert alert-danger" >
<span *ngIf="name.errors.minlength">You must enter atleast 3 characters</span>
<span *ngIf="name.errors.required">This field required</span>
</div>
<div class="form-group">
<label for="alterEgo">Email</label>
<input type="email" class="form-control" id="alterEgo"
[(ngModel)]="model.email" name="alterEgo">
</div>
<br>
<button type="submit" class="btn btn-primary" [disabled]="!formone.form.valid">Submit</button>
</form>
</div>
<div class="col-md-2">
</div>
</div>
</div>
请帮我解决这个问题,
解决方案
您的方法似乎很好(至少对我而言),您可能需要处理一些事情
从输入代码中删除额外的#X(这会通过误导性错误检查引起问题)并尝试name?.errors?.minlength
在检查错误时添加交叉检查名称是否存在。
<input type="text" class="form-control" id="name" required
[(ngModel)]="model.name" name="name" #name="ngModel" minlength="3">
<span *ngIf="name?.errors?.minlength">You must enter atleast 3 characters</span>
您可以在此处查看有关模板驱动的错误处理的更多信息:
快乐编码.. :)
推荐阅读
- python - 当给定特定条件时,通过用户定义的函数在熊猫数据框的列中输入值
- sql-server - 使用列名和数据查询列出表,但不是列名需要来自另一个表的业务列名
- xamarin.forms - Xamarin UWP:视频播放器组件似乎不适用于打开 .NET Native 工具链的编译
- shiny - 在闪亮中使用 includeHTML 显示 html 文件不适用于 renderUI()
- php - While 循环仅显示数据库中的第一行
- delphi - 如何确定数组中的数字是否为偶数
- javascript - 禁用按钮时添加警告
- c++ - 联合类型的模板特化
- laravel - 获取相关数据
- boto3 - AWS 凭证