我有角度反应形式的奇怪问题,特别是" hasError"功能。我检查我的输入是否包含mac地址。函数hasError发送给我,但不显示错误。
我从API获取数据。数据是由邮递员软件发送的,而非我的表格,所以这不是正常的方式。但问题出在这里,我想了解它。
这是我的代码:
component.ts
// form init
const macAddressPattern = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
const ipPattern = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
this.deviceForm = fb.group({
'name': fb.control('', [Validators.required]),
'model': fb.control('', [Validators.required]),
'brand': fb.control('', [Validators.required]),
'mac_address': fb.control('', Validators.compose([Validators.required, Validators.pattern(macAddressPattern)])),
'ip': fb.control('', Validators.compose([Validators.required, Validators.pattern(ipPattern)])),
});
component.html
<mat-form-field class="form-input">
<input matInput formControlName="mac_address" required
placeholder="mac address">
<mat-error *ngIf="deviceForm.controls['mac_address'].hasError('pattern')">
bad mac address // not displayed
</mat-error>
<!--<mat-error *ngIf="deviceForm.controls['mac_address'].hasError('required')">
The field is required
</mat-error>-->
</mat-form-field>
<pre> has error : {{deviceForm.controls.mac_address.hasError('pattern')}} </pre> // has error : true
有什么想法吗?谢谢!
答案 0 :(得分:0)
您可以将语法简化为:
'mac_address': '', [Validators.required, Validators.pattern(macAddressPattern)],
您应该使用另一种语法来处理错误
*ngIf="deviceForm.get('mac_address').hasError('pattern')"
这种语法对我有用。如果它没有,请制作一个沙盒,以便我们可以看到问题并使用它。
答案 1 :(得分:0)
我不知道这是否是最好的方式,但它有效:我模拟用户触摸表单的每个字段以显示错误。
initFormValues() {
this.deviceForm.patchValue(myObj);
// edit mode
if (this.deviceForm.invalid && this.updateForm) {
this.markFormGroupTouched(this.deviceForm);
}
}
public markFormGroupTouched(formGroup: FormGroup) {
Object.values(formGroup.controls).forEach(control => {
control.markAsTouched();
});
}
或es2016
public markFormGroupTouched(formGroup: FormGroup) {
for(let i in formGroup.controls) {
formGroup.controls[i].markAsTouched();
}
}