Angular 角度反应形式验证嵌套字段
我使用的是角度7 我有一个嵌套的反应式表单Angular 角度反应形式验证嵌套字段,angular,angular-reactive-forms,Angular,Angular Reactive Forms,我使用的是角度7 我有一个嵌套的反应式表单 this.salonProfileForm = this.fb.group({ salonName: new FormControl('', [Validators.required]), address: this.fb.group({ city: new FormControl('', [Validators.required]) }) }); get f() { return this.salonProfileFor
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;
}
我有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>
如何验证嵌套的输入字段?
console.log(此.f.address)
您必须访问以下内容:
f.address.controls.city.invalid
编辑
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])
})
});
}
}
移动到.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>
这是必需的
我已将其粘贴到正确的形状中,因此请随时更新您的代码以符合上述要求。仍然会给出相同的错误。此外,webstorm编辑器会给出
未解析变量city
错误。请控制台.log(f.address)
并向我显示输出权限,在运行命令ng build--prod
时,它会给出错误“Property”controls“不存在于类型“AbstractControl”上”。`在我进行上述错误检查的行上。检查这个html和tscontent@AnujTBE尝试为最后一个错误添加一个不同的问题,可能与此答案无关
<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>