Home >Web Front-end >JS Tutorial >Detailed explanation of the implementation method of a complete Angular4 FormText component
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 = ''; @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) { // } }
Component usage
<form-text [(ngModel)]="mobile" [placeholder]="placeholder" [label]="label"></form-text> <p>{{mobile}}</p>
Points to note:
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!