【问题标题】:Unique item name validator in Angular FormArrayAngular FormArray 中的唯一项目名称验证器
【发布时间】:2019-05-28 10:42:07
【问题描述】:

我想验证项目名称文本必须是唯一的。我参考了 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

请帮忙。

【问题讨论】:

  • 如果您在查看 stackblitz 时打开开发者控制台 (F12),您将看到问题。纠正它。然后,检查您正在使用的验证器包实际上是否有一个名为 unique 的验证器。

标签: angular angular-reactive-forms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多