1

I keep having "No value accessor for form control with unspecified name attribute"

some say ngDefaultControl should be added but it does not trigger any change in my component

I tried to implement ControlValueAccessor instead but I get back to the error message above

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
    {

    }
}

What am I doing wrong ? I cant find any example for recent implementation

thanks

n00dl3
  • 21,213
  • 7
  • 66
  • 76
Phil
  • 708
  • 1
  • 11
  • 22
  • read [Never again be confused when implementing ControlValueAccessor in Angular forms](https://blog.angularindepth.com/never-again-be-confused-when-implementing-controlvalueaccessor-in-angular-forms-93b9eee9ee83) – Max Koretskyi Sep 15 '17 at 14:57

2 Answers2

1

You need to tell the injector this is a ControlValueAcessor by creating an injection token with the capabilities of NG_VALUE_ACCESSOR and adding it to the providers of your component :

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]
})
...
n00dl3
  • 21,213
  • 7
  • 66
  • 76
0

been too fast to post here

anyway I found the right tutorial for this

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

enjoy ;-)

Phil
  • 708
  • 1
  • 11
  • 22