Angular FormArray中的唯一商品名称验证器

时间:2019-01-01 11:59:17

标签: angular angular-reactive-forms

我要验证商品名称文本必须唯一。我引用了SO链接,但是链接示例对我不起作用。我试图评论各自的答案,但是我没有那么大的声望。

链接1: Angular - Uniqueness validator in FormArray

链接2: Unique value validation in FormControl of FormArray

下面是我当前的代码:

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()]
    }));
  }

  

  
}

下面是我的HTML代码:

<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示例,但未按我的要求运行:https://stackblitz.com/edit/angular-paqxqs?file=src%2Fapp%2Fapp.component.html

请帮助。

1 个答案:

答案 0 :(得分:2)

只需在*对象的末尾添加?,以确保它不是未定义的。

errors