我有一個嵌套陣列項串列。如果某些專案在“電子設備”中選擇了“Apple”,我想在“Apple Phone(如果適用)”(頂部)中添加驗證作為必填欄位。問題是如何控制不同表單組中的驗證。任何人都可以幫忙嗎?
波紋管影像是我想要驗證的。我想在“電子設備”中選擇“Apple”的任何專案時觸發錯誤訊息。
uj5u.com熱心網友回復:
在創建自定義驗證器之前,我們需要考慮到 Angular 只檢查驗證是否有輸入(或自定義 formControl)并且用戶更改值,或者如果我們手動進行 updateValueAndValidity。
因此,如果我們希望 Angular 在我們更改另一個控制元件時驗證一個控制元件,我們可以采取兩種方法
使用 .html 中的事件更改
<select formControlName="device" (change)="updateAppleForm.get('apple').updateValueAndValidity()">訂閱 FormControl 的 valueChange。那就是我們的功能
settypeList變成了settypeList(x) { 讓 arr = new FormArray([]);
x.typeList.forEach((y) => { //first we create the group const group=this.fb.group( { subQuota: y.subQuota, device: y.device, } ) //subscribe to valueChanges group.get('device').valueChanges.pipe( takeUntil(this.active)) .subscribe(_=>{ setTimeout(()=>{ this.updateAppleForm.get('apple').updateValueAndValidity(); }) }) //and push the group arr.push(group); }); return arr; }
看到我使用“經典” takeWhile 取消訂閱 onDestroy。
active: Subject<any> = new Subject<any>(); //we decalre a subject "active"
//and in ngOnDestroy emit a true and give as completed
ngOnDestroy() {
this.active.next(true);
this.active.complete();
}
我們需要進行的第二次選舉是有兩個或只有一個 FormGroup。如果我們有一個獨特的 FormGroup,我們需要對我們的代碼進行一些更改
我們定義我們的updateAppleForm喜歡
this.updateAppleForm = this.fb.group({
apple: [null,this.requiredIfApple],
sessionList: this.fb.array([])
});
并使用吸氣劑
//instead
//sessionListFormArr:FormArray
//use a getter
get sessionListFormArr(): FormArray {
return this.updateAppleForm.get('sessionList') as FormArray;
}
在 .html 之后,我們洗掉<form [formGroup]="sessionListessionDynamicForm">
<div formArrayName="sessionList">
好吧,我們的自定義驗證器變得像
requiredIfApple(control:AbstractControl)
{
const parent=control.parent;
if (!parent || control.value)
return null;
return parent.value.sessionList.find(x=>x.typeList.find(t=>t.device=='A'))?{inValidApple:"required"}:null
}
你可以在stackblitz中看到
但是您詢問使用組件變數的驗證器。為此,您需要使用 javascript系結
你定義你的 formGroup 像
this.updateAppleForm = this.fb.group({
apple: [null,this.requiredIfApple().bind(this)]
});
你的自定義錯誤就像
requiredIfApple()
{
return (control:AbstractControl)=>{
if (!this.sessionListessionDynamicForm || control.value)
return;
const form=this.sessionListessionDynamicForm.get('sessionList') as FormArray
return form.value.find(x=>
x.typeList.find(t=>t.device=='A'))?
{inValidApple:"required"}:null
}
}
您使用這種方法的分叉堆疊閃電戰。看到我們需要做一個 updateValueAndValidity。在這個堆疊閃電戰中,我使用了使用事件“更改”的方法
uj5u.com熱心網友回復:
當您遍歷 FormArray.controls 并在回圈中使用變數時,例如
*ngFor="let sessionQuota of sessionFormArr.get('typeList')['controls']
該變數是“AbstractControl”,因此您可以使用sessionQuota.errors and sessionQuota.touched,例如
<div *ngIf="sessionQuota.errors && sessionQuota.touched">
error
</div>
順便說一句,我更喜歡有一個功能
getTypeList(index){
return this.sessionFormArr.at(index).get('typeList') as FormArray
}
并迭代getTypeList(i).controls
*ngFor="let sessionQuota of getTypeList(i).controls"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495454.html
