Home > Web Front-end > JS Tutorial > body text

What are the steps required to implement a complete Angular4 FormText component?

php中世界最好的语言
Release: 2018-04-14 14:42:54
Original
1474 people have browsed it

This time I will bring you the steps required to implement a complete Angular4 FormText component, and what are the precautions to implement a complete Angular4 FormText component. The following is a practical case, let's take a look.

This article mainly introduces how to write a complete Angular4 FormText component, share it with everyone, and leave a note for yourself

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) {
  //
 }
}
Copy after login

Component usage

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

Points to note:

Need to configure the providers of the component
Need to implement ControlValueAccessorInterface                                                            

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How js matches and calculates font-size

##Operation modal single load data


The above is the detailed content of What are the steps required to implement a complete Angular4 FormText component?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template