在 Angular 7 中,如果在自定义组件中使用 registerOnChange 和 registerOnTouched 方法时出现错误提示 "registerOnChange is not a function",通常是因为这些方法没有正确实现。
以下是一个示例解决方法:
ControlValueAccessor 接口,并且正确实现了接口中的方法。在你的自定义组件的类定义中添加 ControlValueAccessor 接口,在类中实现 registerOnChange 和 registerOnTouched 方法。import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-custom-control',
templateUrl: './custom-control.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomControlComponent),
multi: true
}
]
})
export class CustomControlComponent implements ControlValueAccessor {
value: any;
// Implement ControlValueAccessor methods
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
// Implement other necessary methods
writeValue(value: any): void {
this.value = value;
}
private onChange(value: any) {
// Handle value change here
}
private onTouched() {
// Handle touch event here
}
}
ngModel 或 formControlName 指令,并且将自定义组件的 [(ngModel)] 或 formControlName 绑定到你的表单控件中。
FormsModule 或 ReactiveFormsModule 导入到你的模块中。import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { CustomControlComponent } from './custom-control.component';
@NgModule({
imports: [
BrowserModule,
FormsModule, // or ReactiveFormsModule
],
declarations: [
AppComponent,
CustomControlComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
通过以上步骤,你应该能够解决 "registerOnChange is not a function" 的错误,并且在 Angular 7 中正确实现自定义组件的双向绑定。