FormArray的FormControl中的唯一值验证

时间:2018-12-25 09:32:40

标签: angular angular-reactive-forms

我正在开发工作表,用户可以在工作表中输入自己的爱好。我已经在hobbyName formcontrol上应用了所需的验证,但是如果有多个以上的兴趣爱好,该如何验证唯一的兴趣爱好名称。

下面是我的ts代码

import { Component,OnInit } from '@angular/core';
import { FormGroup,FormArray,FormBuilder,Validators } from "@angular/forms"
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  jobForm:FormGroup
  constructor(private jobfb:FormBuilder){}

  ngOnInit(){
    this.jobForm = this.jobfb.group({
      hobbies:this.jobfb.array([
        this.createHobbyFormGroup()
      ])
    })
  }

  addHobby(){
    let hobbies = this.jobForm.controls.hobbies as FormArray;
    hobbies.push(this.createHobbyFormGroup());
  }

  

  createHobbyFormGroup(){
    return this.jobfb.group({
      hobbyName:['',Validators.required]
    });
  }

}

下面是我的HTML代码

<button (click)="addHobby()">Add Hobby</button>
<table>
  <tr [formGroup]="hobbyFG" *ngFor="let hobbyFG of jobForm.controls.hobbies.controls;">
    <input formControlName="hobbyName"/>
  </tr>
</table>
<button [disabled]="!jobForm.valid">Submit</button>

每当用户单击添加按钮时,新的FormGroup都会添加到FormArray中。

我无法弄清楚如何验证爱好名称,该名称应该唯一?

请指导。

1 个答案:

答案 0 :(得分:1)

好的,您可以使用RxwebValidators包,我已经实现了它的工作。在我的代码下面共享。

在ts文件中(在应用模块中导入)

    import { RxwebValidators } from '@rxweb/reactive-form-validators';

    export class ProductComponent implements OnInit ,Product {
    public complexForm: FormGroup = this.builder.group({
    'firstName' : ['',[Validators.required,Validators.pattern('^[a-zA-Z0-9]+$')]],
      'lastName': ['', Validators.minLength(5)],
      hobbies:this.builder.array([
        this.createHobbyFormGroup()
      ]),
      'gender' : 'Female',
      'hiking' : false,
      'running' : false,
      'swimming' : false
    });

    addHobby(){
    let hobbies = this.complexForm.controls.hobbies as FormArray;
    hobbies.push(this.createHobbyFormGroup());
  }

  createHobbyFormGroup(){
    return this.builder.group({
      hobbyName:['',RxwebValidators.unique()]
    });
  }



 }

以HTML格式

    <table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">hobby Name</th>
    </tr>
  </thead>
  <tbody>
    <tr [formGroup]="skillGroup" *ngFor="let skillGroup of complexForm.controls.hobbies.controls;let i = index;">
      <th scope="row">{{i+ 1}}</th>
      <td><input type="text" formControlName="hobbyName" class="form-control"  />
    </tr>
  </tbody>
</table>
  <div class="form-group">
    <label>hobbies</label>
    <input class="form-control" type="text" [formControl]="complexForm.controls['hobbies']">
  </div>

我希望这会有所帮助:)