angular - formArray里面的formGroup里面的验证控件
问题描述
如何验证 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 的验证状态
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>
推荐阅读
- node.js - 无法在 linux 上安装 sass
- web-scraping - 使用文本模块进行 PDF 抓取
- c - c 语法的问题 - const * const * 定义
- html - 如何选择所需表单的元素,同时在初始框中显示选择元素的名称(仅限 HTML)?
- node.js - 在 mocha 测试之间重新导入模块
- bash - Bash 脚本自动化:涉及将文件从源复制到目标,在目标执行脚本并将结果从目标复制到源
- javascript - 使用 exec() 在 cmd 行中的电子 js 上执行命令“ADB 设备”
- node.js - 基于环回自定义角色的 ACL 不起作用
- java - 使用相同接口的对象并锁定执行工作的队列
- java - Solace JMS 消费者在重新连接后停止