如何在自定义组件中使用ngModel?

网址:https://embed.plnkr.co/nqKUSPWb6w5QXr8a0wEu/?show=preview

import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

const noop = () => {
};

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CustomInputComponent),
    multi: true
};

@Component({
    selector: 'custom-input',
    template: `
`, providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] }) export class CustomInputComponent implements ControlValueAccessor { //The internal data model private innerValue: any = ''; //Placeholders for the callbacks which are later provided //by the Control Value Accessor private onTouchedCallback: () => void = noop; private onChangeCallback: (_: any) => void = noop; //get accessor get value(): any { return this.innerValue; }; //set accessor including call the onchange callback set value(v: any) { if (v !== this.innerValue) { this.innerValue = v; this.onChangeCallback(v); } } //Set touched on blur onBlur() { this.onTouchedCallback(); } //From ControlValueAccessor interface writeValue(value: any) { if (value !== this.innerValue) { this.innerValue = value; } } //From ControlValueAccessor interface registerOnChange(fn: any) { this.onChangeCallback = fn; } //From ControlValueAccessor interface registerOnTouched(fn: any) { this.onTouchedCallback = fn; } }

使用

//our root app component
import {Component} from '@angular/core'

@Component({
    selector: 'demo-app',
    template: `
        

Form data:{{demoForm.value | json}}

Model data: {{dataModel}}

Write in this wrapper control:
` }) export class AppComponent { dataModel: string = ''; }

原理:

  • 需要继承ControlValueAccessor 。
  • writeValue用来获取ngModel的值,onChangeCallback 用来将ngModel的值传出。每次改变value时都要触发这个函数。
  • 注意当ngmodel传入的值没有改变时,不会触发writeValue。

你可能感兴趣的:(如何在自定义组件中使用ngModel?)