Home > database >  Angular - Using NgControl does not work with writeValue
Angular - Using NgControl does not work with writeValue

Time:01-17

I am a custome control with valueAccessor as below

constructor( @Self() @Optional() public valueControl: NgControl ) {
    if( valueControl ) {
        valueControl.valueAccessor = this;
    }
}

writeValue( values: any ): void {
        if( this.valueControl.control.value) {   // error here because control is undefined
            // Do something 
        }
}

I dont understand why the control is undefined when its injected within the constructor. Any help please?

CodePudding user response:

You're not setting the valueControl on the class i.e. via this

  // bind this custom component to control value accessor
  constructor(@Self() @Optional() public ngControl: NgControl) {
    this.ngControl && (this.ngControl.valueAccessor = this);
  }

Hence this.ngControl, valueControl in your case, is undefined in your writeValue function

  • Related