[英]Validation control inside formGroup inside formArray
如何驗證 formGroup 中的控件,而該控件又位於數組中。
在這種情況下,我想驗證numeroCelular
我有以下內容:
組件.ts
this.formContacto = this.fb.group({
telefonos: this.fb.array([
this.fb.group({
tipo: [''],
numeroCelular: ['', Validators.required],
whatsapp: [],
codigoCiudad: [],
numeroFijo: [],
})
])
});
errorNumeroCelular(i) {
return ((this.formContacto.controls['telefonos'] as FormGroup) as
FormGroup).controls.numeroCelular.hasError('required') ? 'Ingrese un número de celular' : '';
}
組件。html
<mat-form-field appearance="standard">
<mat-label>Número celular</mat-label>
<input matInput formControlName="numeroCelular">
<mat-error *ngIf="errorNumeroCelular()">{{errorNumeroCelular()}}</mat-error>
</mat-form-field>
嘗試這個
this.formContacto = this.fb.group({
telefonos: this.fb.array([
[this.createNewFormGroup()],
[Validators.required])
])
});
createNewFormGroup()
方法正在創建一個 FormGroup,如下所示
createNewFormGroup() {
return this.fb.group({
tipo: [''],
numeroCelular: ['', Validators.required],
whatsapp: [],
codigoCiudad: [],
numeroFijo: [],
})
}
訪問 FormArray 的驗證 state
get yourName(): FormArray {
return this.formContacto.get('telefonos') as FormArray;
}
HTML 模板
<label *ngIf="telefonos.errors?.required">
your msg.
</label>
<label *ngIf="telefonos.controls[i].get('numeroCelular').errors?.required">
your msg.
</label>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.