Anu*_*TBE 5 angular angular-reactive-forms
我正在使用Angular 7
我有一个嵌套的反应形式
this.salonProfileForm = this.fb.group({
salonName: new FormControl('', [Validators.required]),
address: this.fb.group({
city: new FormControl('', [Validators.required])
})
});
get f() {
return this.salonProfileForm.controls;
}
Run Code Online (Sandbox Code Playgroud)
我有这样的 HTML 表单
<input type="text" formControlName="salonName" required />
<ng-container *ngIf="submitted && f.salonName.invalid && (f.salonName.dirty || f.salonName.touched)">
<small *ngIf="f.salonName.errors.required">
Salon name is required
</small>
</ng-container>
<div formGroupName="address">
<input type="text" formControlName="city" />
<ng-container *ngIf="submitted && f.city.invalid && (f.city.dirty || f.city.touched)">
<small *ngIf="f.city.errors.required">
city is required
</small>
</ng-container>
</div>
Run Code Online (Sandbox Code Playgroud)
但这会在城市输入ng-container字段上产生错误,如下所示
ERROR TypeError: Cannot read property 'invalid' of undefined
Run Code Online (Sandbox Code Playgroud)
如何验证嵌套的输入字段?
console.log(this.f.地址)
您必须像下面这样访问:
f.address.controls.city.invalid
Run Code Online (Sandbox Code Playgroud)
编辑
export class Home implements OnInit {
salonProfileForm : FormGroup;
ngOnInit() {
this.salonProfileForm = new FormGroup({
'salonName': new FormControl('', [Validators.required]),
'address': new FormGroup({
'city': new FormControl('', [Validators.required])
})
});
}
}
Run Code Online (Sandbox Code Playgroud)
移至.html模板
<form [formGroup]="salonProfileForm " (ngSubmit)="onSubmit()">
<div formGroupName="address">
<input type="text" formControlName="city" />
<ng-container *ngIf="!salonProfileForm.get('address.city').valid && salonProfileForm.get('address.city').touched">
<span>This is required</span>
</ng-container>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
我已经粘贴了它有效的形状,因此请随时更新您的代码以适应上述内容。