Angular 2 - ControlValueAccessor - 如何实现?

Angular 2 - ControlValueAccessor - How to implement?

我一直有 "No value accessor for form control with unspecified name attribute"

有人说应该添加 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
    {

    }
}

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

谢谢

您需要通过创建具有 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]
})
...

太快了post这里

总之我找到了合适的教程

https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#implementing-controlvalueaccessor

享受 ;-)