我正在尝试通过在 Angular 中实现 ControlValueAccessor 和 Validator 来创建自定义电话输入组件,但我遇到了 mat-error 未触发的问题。 FormGroup 似乎可以工作,因为它检测值更改并正确识别电话号码是否无效。 FormGroup 错误包括 { "notValidNumber": true },但不知何故电话输入没有得到其 errorState 应该为 true 的信息。
是否有手动方式触发输入组件 mat-form-field 的 errorState,或者您能建议任何其他解决方案吗?
这里是父组件的代码:
<form [formGroup]="formGroup">
...
<div>
<app-phone-input formControlName="phone" [phoneNumber]="this.entryAddEditService.entryObject.mobile!">
</app-phone-input>
</div>
...
</form>
this.formGroup = this.formBuilder.group({
...
phone: [this.entryAddEditService.entryObject.mobile],
...
});
这里是输入组件的代码:
<mat-form-field floatLabel="always">
<mat-label>{{ "sk.entry.infoPhone" | translate }}:</mat-label>
<input matInput id="info-phone"/>
<mat-error>
"}}
</mat-error>
</mat-form-field>
@Component({
selector: 'app-phone-input',
templateUrl: './phone-input.component.html',
styleUrls: ['./phone-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: PhoneInputComponent,
multi: true
},
{
provide: NG_VALIDATORS,
useExisting: PhoneInputComponent,
multi: true
}
]
})
export class PhoneInputComponent implements ControlValueAccessor, Validator {
...
validate(_: AbstractControl): ValidationErrors | null {
if (this.phoneInput && !this.phoneInput.isValidNumber() && this.phoneInput.getNumber()) {
return { "notValidNumber": true };
}
return null;
}
...
我希望它应该显示用红色边框包围的输入并显示我的错误消息。