Home  >  Article  >  Web Front-end  >  Write a complete Angular4 FormText component method

Write a complete Angular4 FormText component method

小云云
小云云Original
2018-01-18 11:03:091328browse

This article mainly introduces how to write a complete Angular4 FormText component. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Component definition


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 = &#39;&#39;;
 @Input() placeholder: string=&#39;&#39;;

 @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) {
  //
 }

}

Component usage


<form-text [(ngModel)]="mobile" [placeholder]="placeholder" [label]="label"></form-text>
<p>{{mobile}}</p>

Requires attention Points:

1. Need to configure the providers of the component
2. Need to implement the ControlValueAccessor interface

Related recommendations:

Angular4 Subscription and Cancel detailed explanation

angular4 actual project construction detailed explanation

How to solve the warning when Angular4 binds html content

The above is the detailed content of Write a complete Angular4 FormText component method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn