【问题标题】:Angular 2 - ControlValueAccessor - How to implement?Angular 2 - ControlValueAccessor - 如何实现?
【发布时间】:2017-08-22 08:49:00
【问题描述】:

我一直有“未指定名称属性的表单控件的无值访问器”

有人说应该添加 ngDefaultControl,但它不会触发我的组件中的任何更改

我尝试改为实现 ControlValueAccessor,但我回到上面的错误消息

import { Component, OnInit,Input,OnChanges,SimpleChange } from '@angular/core';
import { ControlValueAccessor } from "@angular/forms";

import { ProductsService } from '../../pages/products/products.service';

@Component({
    selector: 'my-product-input',
    templateUrl: './productInput.component.html',
    styleUrls: ['./productInput.component.css'],
})

export class ProductInputComponent implements OnInit,OnChanges,ControlValueAccessor {

    onChange;

    @Input('productID') productID:number=null;

    private product:any;

    constructor(
        private productsService: ProductsService,
        ) {}

    ngOnInit() {
        this.getProduct();
    }

    getProduct() ...

    ngOnChanges(changes: { [propName: string]: SimpleChange }) {
        ... never gets triggered
    }

    writeValue( value : any ) : void {
        this.productID=value;
        this.getProduct();
    }

    registerOnChange( fn : any ) : void {
        this.onChange = fn;
    }

    // not sure about this entry
    change( $event ) {
        this.onChange($event.target.textContent);
    }

    setDisabledState( _isDisabled : boolean ) : void {
    }

    registerOnTouched(_fn: any):void
    {

    }
}

我做错了什么?我找不到任何最近实施的例子

谢谢

【问题讨论】:

标签: angular custom-controls


【解决方案1】:

您需要通过创建具有NG_VALUE_ACCESSOR 功能的注入令牌并将其添加到组件的提供程序来告诉注入器这是一个 ControlValueAcessor:

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

@Component({
    selector: 'my-product-input',
    templateUrl: './productInput.component.html',
    styleUrls: ['./productInput.component.css'],
    providers: [MY_VALUE_ACCESSOR]
})
...

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2018-04-28
      • 2017-03-19
      • 2019-06-06
      • 2017-04-03
      • 2019-12-02
      • 2017-06-25
      • 1970-01-01
      • 2020-08-17
      相关资源
      最近更新 更多