import { Component, forwardRef } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Component({
selector: 'app-custom-input',
template:
,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true
}
]
})
export class CustomInputComponent implements ControlValueAccessor {
value: any = '';
// 发送将控件值写回表单的信号 propagateChange: any = () => {};
// 发送失败信号 propagateTouch: any = () => {};
// 写回表单 writeValue(value: any) { this.value = value; }
// 注册发射器 registerOnChange(fn: any) { this.propagateChange = fn; }
// 注册失败发射器 registerOnTouched(fn: any) { this.propagateTouch = fn; }
// 处理输入变化 handleInputChange(event: any) { this.value = event.target.value; this.propagateChange(this.value); }
// 处理控件失去焦点 handleInputBlur() { this.propagateTouch(); } }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { CustomInputComponent } from './custom-input/custom-input.component';
@NgModule({ declarations: [CustomInputComponent], imports: [ CommonModule, FormsModule, ReactiveFormsModule ], exports: [ FormsModule, ReactiveFormsModule, CustomInputComponent ] }) export class CustomFormsModule { }