[英]Custom Validation for dynamically generated textboxes in Angular
動態生成文本框的代碼 uisng *ngFor
<tr *ngFor="let computer in _Computers; let i = index;">
<td>{{computer.Name}}</td><td>{{computer.Optional}}</td>
<td> <input matInput [formControl] = "frmCtrl" name="UnitofPrice" [(ngModel)]="computer[i]">
</td>
<td>{{computer.UnitofPrice}}</td>
Typescript碼
public frmCtrl: FormControl = new FormControl('', this.customValidator());
customValidator() {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if ((!control.value)) {
return { 'textRequired': true };
}
return null;
};
}
上面的代碼工作正常。 也就是說,只要文本框為空,它就會顯示錯誤。 假設,我只想驗證基於計算機列表的“可選”屬性的文本框。 在這里,如何將計算機 ID 或可選屬性傳遞給自定義驗證器 function? 請建議。
我會使用一個表單和表單數組,此外,你現在擁有的是一個用於整個數組的表單控件,所以我看不出它對你的數組是如何工作的。
此外,您編寫的驗證器基本上是required
的驗證器,因此您可以為此使用內置的驗證器。 所以我建議如下:
我已經硬編碼_Computers
數組,我構建了表單,我循環了_Computers
並將formcontrols 添加到了formarray。 基於Optional
屬性,我僅為那些Optional
值為false
的單價設置了Validators.required
。 在這里,我將 2 個表單控件推送到數組中的每個表單組, name
和unitOfPrice
,您可以推送任何您想要的數量。
我為formarray制作了一個getter,只是為了更容易訪問。 總而言之,代碼如下所示:
_Computers = [
{ Name: 'name1', Optional: true, UnitOfPrice: null },
{ Name: 'name2', Optional: false, UnitOfPrice: null },
];
myForm!: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
computers: this.fb.array([]),
});
this._Computers.forEach((x: any) => {
if (x.Optional) {
this.computersArr.push(this.fb.group({
name: [x.Name],
unitOfPrice: [null]
}));
} else {
this.computersArr.push(this.fb.group({
name: [x.Name],
unitOfPrice: [null, [Validators.required]]
}));
}
});
}
get computersArr() {
return (this.myForm.get('computers') as FormArray).controls;
}
我一直很懶,在這里使用了any
,請輸入您的數據!
然后模板將顯示表單,如果它有這樣的驗證器,我們可以顯示一條 required 消息:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div formArrayName="computers">
<div *ngFor="let computer of computersArr; let i = index">
<div [formGroupName]="i">
<label>{{computer.get('name').value}}</label>
<input formControlName="unitOfPrice" />
<small *ngIf="computer.get('unitOfPrice').hasError('required')">Required!!</small>
</div>
</div>
</div>
</form>
以上是使用div
的,但您可以輕松地為表復制相同的內容。
這是一個STACKBLITZ供您參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.