Angular react 形式验证嵌套字段

标签 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;
}

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

相关文章:

forms - 具有嵌套组的 Angular 4 动态表单

angular - 有没有办法默认为 ng build 设置 --base-href,但不是为 ng serve?

angular - "No value accessor for form control with path"尽管使用 formBuilder.control

angular - 如何在 Angular 5 响应式(Reactive)表单输入中使用管道

angular - 剑道 : Insert a FormGroup at a top into a FormArray

仅针对用户输入的 Angular 去抖动

http请求期间的Angular2链接函数失败

javascript - 使用 Angular 2 进行动态表单验证

Angular2 - 在不同环境中执行端到端测试

javascript - 检查 Angular 中的 "mode"可见打印还是隐藏打印