本文主要介绍了如何编写一个完整的Angular4 FormText 组件,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。
组件定义
import { Component, Output, Input, forwardRef, EventEmitter} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; @Component({ selector: 'form-text', template: ` <p > <label>{{label}}:</label> <input type="text" [(ngModel)]="value" placeholder="{{placeholder}}" > </p> `, 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>
需要注意的点:
需要配置组件的providers
相关推荐:
以上是详解一个完整的Angular4 FormText 组件的实现方法的详细内容。更多信息请关注PHP中文网其他相关文章!