[英]Add dynamic form fields and validations to formArray in Angular
我正在嘗試構建一個動態表單,其中字段名稱及其驗證將來自 API
所以我正在創建一個簡單的表單,里面有一個 formArray,如下所示:
this.myForm = this.formBuilder.group({
dynamicFields: this.formBuilder.array([]) // where I will be pushing the custom fields and their validations
});
只是為了測試,我正在嘗試添加一個字段“國家”,有 2 個驗證(必需,minLength 為 22)
這就是我正在做的事情:
let customControl = this.fb.control('country', [ Validators.required, Validators.min(10) ]);
(this.myForm.get('dynamicFields') as FormArray).push(customControl);
我還創建了波紋管吸氣劑以在我的模板中使用它
getDynFields() {
return this.myForm.get('dynamicFields') as FormArray;
}
這是模板:
<form [formGroup]="myForm">
<div formArrayName="dynamicFields">
<div *ngFor="let control of getDynFields().controls; let i = index">
<mat-form-field>
<input
[formControlName]="i"
matInput
type="text"
placeholder="{{ control.value }}"
/>
</mat-form-field>
</div>
</div>
</form>
正在發生的事情(如下所示)是對於字段值和占位符,我正在預填充“國家”(我只希望占位符為“國家”,並且該值當然應該為空)第二個問題是只有必需的驗證有效, minLength 沒有做任何事情
提前致謝。
FormControl 在初始化時將'state'
或默認值作為第一個參數。 同樣對於最小長度,您應該使用Validators.minLength(n)
。
constructor(formState: any = null, validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])
而不是這個
let customControl = this.fb.control('country', [ Validators.required, Validators.min(10) ]);
你應該做這個
let customControl = this.fb.control('', [ Validators.required, Validators.minLength(10) ]);
Validators.min() 與 Validators.minLength()
您正在使用Validators.min() 。 這旨在檢查數字輸入值,而不是獲取字符串的長度:
let customControl = this.fb.control('country', [ Validators.required, Validators.min(10) ]);
let customControl = this.fb.control('country', [ Validators.required, Validators.minLength(10) ]);
FormControl 的第一個參數是它的值
FormControl 的第一個參數是它的值。 您在示例中設置了“國家”的值:
let customControl = this.fb.control('country', [ Validators.required, Validators.minLength(10) ]);
如果您將其設置為 null,您將看到您設置的任何占位符。
let customControl = this.fb.control(null, [ Validators.required, Validators.minLength(10) ]);
您可以在模板中實現所需的占位符。 作為字符串或對某些對象屬性的引用。
對於最小長度,請使用 Validators.minLength(22)
請參閱: https://angular.io/api/forms/Validators#minLength了解更多信息。
min(10) 用於添加驗證,因為最小值可以是 10。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.