亲宝软件园·资讯

展开

如何编写一个完整的Angular4 FormText 组件

mntx 人气:0

本文主要介绍了如何编写一个完整的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.需要实现ControlValueAccessor接口

加载全部内容

相关教程
猜你喜欢
用户评论