我有一个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}}部分。
答案 0 :(得分:0)
选择器是罪魁祸首,将其改为
selector: '[uniqueValidator][ngModel]'
工作了!