0
的陣列動態形式I有一個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">
注:我已經包含在@NgModule
的declarations
部分UniqueValidator
。
我在您的html – yurzui
中看不到'ngModelGroup'!剛纔弄明白了:)傻了! –