我在我的项目Stackblitz中有loginForm
但是我在’formControlName’上收到错误: 错误TypeError:无法读取未定义的属性’get’ Object.eval [as updateDirectives](LoginComponent ….
参考你的代码 stackblitz
这是你的表格
this.loginForm = this.fb.group({ email: ['', Validators.required ], password: ['', Validators.required] });
并在HTML中 你错过了表格名称
<div class="form-group"> <app-input-field formControlName="email"></app-input-field> <div class="alert alert-danger" *ngIf="loginForm.get('email').dirty && personalProfileForm.get('email').hasError('required')"> email Required </div> <app-input-field formControlName="password"></app-input-field> <div class="alert alert-danger" *ngIf="loginForm.get('password').dirty && personalProfileForm.get('password').hasError('required')"> password Required </div> </div>
只需更换 personalProfileForm 同 loginForm 在你的HTML中
personalProfileForm
loginForm
此外,@ dince12的建议是完美的,以使您的HTML代码看起来更容易阅读,欢呼!
如果您想了解有关该示例的更多详细信息,请参阅以下文章: http://jasonwatmore.com/post/2018/05/10/angular-6-reactive-forms-validation-example 以下是一个小例子:
像这样创建公共财产
public get myform() { return this.myform.controls; }
并像这样使用它
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && myform.firstName.errors }" /> <div *ngIf="submitted && myform.firstName.errors" class="invalid-feedback"> <div *ngIf="myform.firstName.errors.required">First Name is required</div> </div>