无法以与 Angular 文档中相同的方式访问它,因此必须先获取 FormGroup 实例并在其中找到 FormControl 实例。我想知道为什么?这个例子有效:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="myForm.controls.username.invalid" class="alert alert-danger">
username is required
</div>
</div>
虽然这会引发错误(仅在 *ngIf 语句中存在差异):
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="username.invalid" class="alert alert-danger">
username is required
</div>
</div>
无法读取未定义的属性“无效”
表单组件:
import {Component} from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'sign-up',
templateUrl: 'app/sign-up.component.html'
})
export class SignUpComponent {
myForm = new FormGroup({
username: new FormControl('username', Validators.required),
password: new FormControl('', Validators.required),
});
}