本文主要介紹了如何編寫一個完整的Angular4 FormText 組件,分享給大家,也給自己留個筆記
組件定義
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.需要配置組件的providers
2.需要實現(xiàn)ControlValueAccessor接口
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com