动态表单中的自定义验证对项目数组

时间:2017-06-08 03:04:34

标签: angular validation angular2-forms

我有一个Person []可以动态编辑,一次一个,所以我有以下内容:

<template ngFor let-indx="index" let-persons [ngForOf]="persons">
    <div *ngIf="!person.isEditing">
        <h4>{{person.name}}</h4>
    </div>
    <div *ngIf="person.isEditing">
        <form #addNewGuestForm="ngForm" novalidate>
            <input [(ngModel)]="person.name" #personName="ngModel" required maxlength="50" minlength="2">
        </form>
    </div>
    <button (click)="person.isEditing=!person.isEditing">Edit/Save</button>
</template>

注意:表单由* ngIf包装。

问题:如何验证名称是唯一的,并且不会与人员数组中的其他名称发生冲突?我尝试了以下操作,但我得到了经典之作:Can't bind to 'persons' since it isn't a known property of 'input'

@Directive({
    selector: '[uniqueValidator][ngModelGroup]',
    providers: [{ provide: NG_VALIDATORS, useExisting: UniqueValidator, multi: true }]
})
export class UniqueValidator implements Validator {
    @Input() persons: Person[];
    validate(control: FormGroup): { [key: string]: any } {
        //validation against other items in persons
    }
}

并且html变为:

<input uniqueValidator [persons]="persons" [(ngModel)]="person.name" #personName="ngModel" required maxlength="50" minlength="2">

注意:我已将UniqueValidator添加到@NgModule的{​​{1}}部分。

1 个答案:

答案 0 :(得分:0)

选择器是罪魁祸首,将其改为

selector: '[uniqueValidator][ngModel]'

工作了!