我正在使用TypeScript学习Angular 5。我是全新的。我现在正在尝试构建一个表单并验证它。但它不能正常工作。请参阅下面的代码。
这是我的组成部分。
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
animations: [routerTransition()]
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
errors = [];
constructor(private fb: FormBuilder, public router: Router, private globals: GlobalsService, private http: Http) {
}
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl("", Validators.required),
password: new FormControl("")
});
}
onLoggedin(formData) {
alert("Submit form");
}
}
如您所见,我正在设置"必需"电子邮件字段上的验证属性。 这是我的HTML。
<div class="login-page" [@routerTransition]>
<div class="row justify-content-md-center">
<div class="col-md-4">
<img src="assets/images/logo.png" width="150px" class="user-avatar" />
<h1>Yo Cash Flow</h1>
<div class="alert alert-danger" *ngFor="let error of errors">
<strong>{{ error.msg }}</strong>
</div>
<form [formGroup]="loginForm" role="form" (ngSubmit)="onLoggedin(loginForm.value)">
<div class="form-content">
<div class="form-group">
<input type="text" name="email" formControlName="email" class="form-control input-underline input-lg" placeholder="Email">
<div *ngIf="loginForm.controls['email'].errors.required" class="text-danger">Email is required</div>
</div>
</div>
<button type="submit" class="btn rounded-btn"> Log in </button>
<a class="btn rounded-btn" [routerLink]="['/signup']">Sign up</a>
</form>
</div>
</div>
</div>
正如您所看到的,我试图单独显示错误。我的意思是&#34;必需&#34;属性,我正在检索错误消息,如error.required。但它没有用。但当我尝试使用&#34;有效&#34;如下所示,它正在发挥作用。
loginForm.controls['email'].invalid
但是我想单独检索错误,因为我想为不同的错误显示不同的消息。请问我该如何解决这个问题?当我使用&#34; loginForm.controls [&#34; email&#34;]时,为什么它不起作用.error.required&#34;?请问为不同的验证规则显示不同消息的正确方法是什么?
答案 0 :(得分:2)
您可以使用errors
属性,如下所示:
loginForm.controls['email'].errors
如果没有错误,它将返回null,否则它将返回如下对象:
{ required : true }
然后,您只需创建一个将返回人类可读错误消息的函数,如下所示:
getErrorMessage(controlName, displayName) {
let result = "";
let errors = loginForm.controls[controlName].errors;
if (errors.required) {
result += (displayName + " is required.");
}
if (errors.whatever) {
result += "Whatever you like";
}
return result;
}
答案 1 :(得分:0)
必须在按钮的(loginForm.valid)
或[disabled]属性内使用*ngIf
。这会自动从ts文件中检查表单是否经过验证。
此外,您可以在ts文件中编写验证信息:
new FormControl('',[Validators.required])
像这样
答案 2 :(得分:0)
我刚刚花了几个小时尝试在项目中调试此问题,但在我看来,该问题正在使用:
<input type="checkbox" formControlName="testing" />
代替:
<input type="checkbox" [formControl]="form.controls['testing']" />
在我的情况下,使用form.AddControl()动态添加FormControl“测试”,这是执行名称绑定的第二种方法,也将模型绑定到输入。
希望这可以帮助解决此问题的人!