Home >Web Front-end >JS Tutorial >Detailed explanation of the implementation method of a complete Angular4 FormText component

Detailed explanation of the implementation method of a complete Angular4 FormText component

小云云
小云云Original
2018-05-17 16:58:571817browse

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>

Points to note:

  1. Providers of the component need to be configured

Related recommendations:

Angular4 form response function sample analysis

CSS style sample code for how to display content in Angular4

Detailed explanation of instances of Router class in Angular4

The above is the detailed content of Detailed explanation of the implementation method of a complete Angular4 FormText component. 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