编写一个完整的Angular4 FormText 组件

前端之家收集整理的这篇文章主要介绍了编写一个完整的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.需要配置组件的providers2.需要实现ControlValueAccessor接口

原文链接:https://www.f2er.com/angularjs/145718.html

猜你在找的Angularjs相关文章