Search code examples
angularformsform-controlcontrolvalueaccessor

Why writeValue called after detroy component which implements ControlValueAccessor?


I have implemented ControlValueAccessor in my own primitive component. Its code you see: there (plunker)

In parent component, I use my with ng-if directive. I can hide and show my component through checkbox. Component inits and destroys each times but writeValue function call a lot of times. Please check my code at plunker

Why is this happening? How I can fix this issue?


Solution

  • You need to recreate the control:

      resetValue() {
        this.name = new FormControl('initial');
        this.name.setValue('has been reset');
      }
    

    As @Сергей mentioned the reason is because every time when ControlValueAccessor component created, it register its callback functions in private property of formControl (for example, _onChange). This is array, which accumulate these functions. One of the solutions is creating new FormControl.