组件定义
import { Component,Output,Input,forwardRef,EventEmitter} from '@angular/core'; import {ControlValueAccessor,NG_VALUE_ACCESSOR} from '@angular/forms'; @Component({ selector: 'form-text',template: ` <div > <label>{{label}}:</label> <input type="text" [(ngModel)]="value" placeholder="{{placeholder}}" > </div> `,providers: [ { provide:NG_VALUE_ACCESSOR,useExisting:forwardRef(()=>FormTextComponent),multi:true } ] }) export class FormTextComponent implements ControlValueAccessor { @Input() label:string = ''; @Input() placeholder: string=''; @Output() onChange: EventEmitter<any> = new EventEmitter<any>(); 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) { // } }
组件使用
<form-text [(ngModel)]="mobile" [placeholder]="placeholder" [label]="label"></form-text> <p>{{mobile}}</p>
需要注意的点:
1.需要配置组件的providers2.需要实现ControlValueAccessor接口