首页 > 解决方案 > FormArray 中的验证问题

问题描述

我是 Angular 的新手,我目前正在用 Angular 建立一个网站,我面临一个我无法用 Angular 文档解决的问题我不太了解问题背后发生了什么。

简而言之,我有一个 formArray(updateAddress),其中包含一个 formGroup 和一些 formControl,我很难对其进行验证。

代码 HTML:

<form [formGroup]="profileForm">
<div *ngFor="let add of updateAddress().controls; let addIndex=index">
    <div formArrayName="updateAddress">
      <div [formGroupName]="addIndex">
        <label>
          Rua:
          <input type="text" formControlName="address">
        </label>
        <div
          *ngIf="profileForm.get('add.address')?.invalid && (address.get('add.address')?.dirty || profileForm.get('add.address')?.touched)">
          <div *ngIf="profileForm.get('add.address')?.errors?.required">
            Tem de escrever a rua da sua loja.
          </div>
        </div>
<button (click)="removeAddress(addIndex)">Remover</button>
      </div>
    </div>
  </div>
  <button type="button" (click)="addAddress()">Adicionar Morada</button>
</form>

代码 TS:

  profileForm: FormGroup;

  control: any;

  
  constructor(
              public formBuilder: FormBuilder,
              private cd: ChangeDetectorRef
             ) {

    this.profileForm = this.formBuilder.group({
      file: [''],
      name: new FormControl('', [Validators.required, Validators.pattern('[a-zA-Z ]*')]),
      email: new FormControl('',  [Validators.required, Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")]),
      password: new FormControl('',[Validators.required, Validators.minLength(7),Validators.pattern('(?=.*[A-Za-z])(?=.*[0-9])(?=.*[$@$!#^~%*?&,.<>"\'\\;:\{\\\}\\\[\\\]\\\|\\\+\\\-\\\=\\\_\\\)\\\(\\\)\\\`\\\/\\\\\\]])[A-Za-z0-9\d$@].{7,}')]),
      password2: new FormControl('', Validators.required),
      nif: new FormControl('',[Validators.required, Validators.pattern('\\d{9}')]),
      birthDate: new FormControl('',[Validators.required, Validators.pattern("^(0[1-9]|[12][0-9]|3[01])[/.](0[1-9]|1[012])[/.](19|20)\\d\\d$") ]),
      phoneNumber: new FormControl('', [Validators.required, Validators.pattern('\\d{9}')]),
      updateAddress: new FormArray([], Validators.required)
    });
   }

  updateAddress(): FormArray {
        return this.profileForm.get("updateAddress") as FormArray
  }

  newAddress(): FormGroup {
      return this.formBuilder.group({
        address: new FormControl('', Validators.required),
        address2: new FormControl('', Validators.required),
        postalCode: new FormControl('', Validators.required),
        city: new FormControl('', Validators.required),
        area: new FormControl('', Validators.required)
      })
  }

  addAddress() {
      this.updateAddress().push(this.newAddress());
  }
  
  removeAddress(addIndex:number) {
    this.updateAddress().removeAt(addIndex);
  }

我真的无法解决此验证中的问题,因为验证感觉就像它通过但在网页中没有出现任何错误我也不知道我是否以正确的方式接近这个。

验证验证的图像正在工作,因为提交被禁用但当它应该在“Rua”输入下发送时没有发送错误

如果有人可以指导或帮助我,我将很高兴!

更新

正如我所说,我认为验证在后台有效,但应该出现的错误文本没有出现,因为我没有正确地获取 ngIf(我认为)

标签: angulartypescript

解决方案


一些需要注意的事项

您可以使用如下方式启动您的表单FormBuilder

    this.profileForm = this.formBuilder.group({
      file: [''],
      name: ['', [Validators.required, Validators.pattern('[a-zA-Z ]*')]],
      email: ['',  [Validators.required, Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")]],
      password: ['',[Validators.required, Validators.minLength(7),Validators.pattern('(?=.*[A-Za-z])(?=.*[0-9])(?=.*[$@$!#^~%*?&,.<>"\'\\;:\{\\\}\\\[\\\]\\\|\\\+\\\-\\\=\\\_\\\)\\\(\\\)\\\`\\\/\\\\\\]])[A-Za-z0-9\d$@].{7,}')]],
      password2: ['', Validators.required],
      nif: ['',[Validators.required, Validators.pattern('\\d{9}')]],
      birthDate: ['',[Validators.required, Validators.pattern("^(0[1-9]|[12][0-9]|3[01])[/.](0[1-9]|1[012])[/.](19|20)\\d\\d$") ]],
      phoneNumber: ['', [Validators.required, Validators.pattern('\\d{9}')]],
      updateAddress: this.formBuilder.array([], Validators.required)
    });

    newAddress(): FormGroup {
      return this.formBuilder.group({
        address: ['', Validators.required],
        address2: ['', Validators.required],
        postalCode: ['', Validators.required],
        city: ['', Validators.required],
        area: ['', Validators.required]
      })
  }

您也可以更改updateAddress为吸气剂

  get updateAddress(): FormArray {
    return this.profileForm.get("updateAddress") as FormArray
  }

对问题

我相信问题在于您如何尝试检索错误

尝试formGroup.get('control_name').errors在您的情况下使用,验证应用于 formArray 内的控件,因此我们需要访问它并获取错误,例如

add.get('address').errors?.required

下面是一个示例 html。

  <ng-container formArrayName="updateAddress">
    <div *ngFor="let add of updateAddress.controls; let addIndex=index">
      <div [formGroupName]="addIndex">
        <label>
          Rua:
          <input type="text" formControlName="address">
        </label>

        <div *ngIf="add.get('address').invalid && (add.get('address').dirty || add.get('address').touched)">
          <div *ngIf="add.get('address').errors?.required">
            Tem de escrever a rua da sua loja.
          </div>
        </div>
        <button (click)="removeAddress(addIndex)">Remover</button>
      </div>
    </div>
    <button type="button" (click)="addAddress()">Adicionar Morada</button>
  </ng-container>

你可以看看这个 stackblitz 演示

编辑

要为表单初始化值,您可以使用setValuepatchValue。像下面的东西

   this.updateAddress.at(0).setValue({
      address: "My Address",
      address2: "My Address 2",
      postalCode: "77777",
      city: "Helsinki",
      area: "Some street"
    });

看这个演示


推荐阅读