Unique item name validator in Angular FormArray

只愿长相守 提交于 2019-12-23 20:03:59

问题


I want validate the item name text must be unique. I have refered SO links, but links examples are not working for me. I tried to comment on respective answer, but I don't have a much reputation to do that.

Link 1: Angular - Uniqueness validator in FormArray

Link 2 : Unique value validation in FormControl of FormArray

below is my current code:

import { Component,OnInit } from '@angular/core';
import { FormGroup,FormBuilder,FormArray } from "@angular/forms"
import { RxwebValidators } from "@rxweb/reactive-form-validators"


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  implements OnInit {

public uniqueRowForm: FormGroup; 

constructor(private fb:FormBuilder){

}


ngOnInit() {
  this.uniqueRowForm  = this.fb.group({
    items:this.fb.array([]),
  });
  this.adduserItem();
}

  

  adduserItem(){
    let items = <FormArray>this.uniqueRowForm.controls.items;
    items.push(this.fb.group({
      name:['',RxwebValidators.unique()]
    }));
  }

  

  
}

below is my HTML code:

<button (click)="adduserItem()">Add Item </button>
 <table class="table">
  <thead>
    <tr>
      <th scope="col">Item</th>
    </tr>
  </thead>
  <tbody>
    <tr [formGroup]="item" *ngFor="let item of uniqueRowForm.controls.items.controls;let i = index;">
     <td><input type="text" formControlName="name" class="form-control"  />
     <span *ngIf="item.controls.name.errors.unique">not unique</span>
     </td>
    </tr>
  </tbody>
</table>

Stackblitz example but not working as per my requirement : https://stackblitz.com/edit/angular-paqxqs?file=src%2Fapp%2Fapp.component.html

Please help.


回答1:


Just add ? at the end of your errors object to insure that it is not undefined.

<span *ngIf="item.controls.name.errors?.unique">not unique</span>


来源:https://stackoverflow.com/questions/53995239/unique-item-name-validator-in-angular-formarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!