gpt4 book ai didi

Angular react 形式验证嵌套字段

转载 作者:行者123 更新时间:2023-12-04 14:19:19 25 4
gpt4 key购买 nike

我正在使用 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;
}

我有这样的 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>

但这会在城市输入 ng-container 字段上产生错误 as

ERROR TypeError: Cannot read property 'invalid' of undefined

如何验证嵌套的输入字段?

console.log(this.f.address)

enter image description here

最佳答案

您必须像下面这样访问:

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>

我已将其粘贴到有效的形状中,因此请随时更新您的代码以适应以上内容。

关于 Angular react 形式验证嵌套字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56717189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com