我正在为表单使用自定义组件,我希望在触摸字段或无效字段以及提交表单时进行验证,在文本字段周围显示红色边框的内容是什么,但我无权访问内部表单自定义组件以获取表单的这些状态。代码类似于以下内容。
<form [formGroup]="form" (submit)="submitFrom()">
<app-from-input FromControlName="name"></app-from-input>
</form>
export class AppComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
name: new FormControl('', Validators.required)
});
}
submitFrom() {
console.log('form submited')
}
}
@Component({
selector: 'app-from-input',
template: `<input type="text" (input)="onChanged($event.target.value)" (blur)="onTouchend()">`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FormInputComponent),
multi: true
}
],
styleUrls: ['./app.component.scss']
})
export class FormInputComponentv, ControlValueAccessor {
form: FormGroup;
valueOfinput: string;
onChanged: (e) => void;
onTouchend: () => void;
constructor(){
}
writeValue(value): void {
this.valueOfinput = value ? value : '';
}
registerOnChange(fn: (rating: number) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
}