本文主要介紹如何寫一個完整的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>
2.需要實作ControlValueAccessor介面
以上是寫一個完整的Angular4 FormText 元件方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!