本文主要介绍了如何编写一个完整的Angular4 FormText 组件,分享给大家,也给自己留个笔记
组件定义
@Component({
selector: 'form-text',template: `
`,providers: [
{
provide:NG_VALUE_ACCESSOR,useExisting:forwardRef(()=>FormTextComponent),multi:true
}
]
})
export class FormTextComponent implements ControlValueAccessor {
selector: 'form-text',template: `
@Input() label:string = '';
@Input() placeholder: string='';
@Output() onChange: EventEmitter
public innerValue: any;
public changeFn: Function = () => {};
get value(): any {
return this.innerValue;
};
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
this.changeFn(v);
}
}
writeValue(value: any) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
registerOnChange(fn: any) {
this.changeFn = fn;
}
registerOnTouched(fn: any) {
//
}
}
组件使用
{{mobile}}
需要注意的点:
1.需要配置组件的providers 2.需要实现ControlValueAccessor接口
原文链接:https://www.f2er.com/js/35155.html