Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why when you update a ControlValueAccessor you dont trigger the ngOnChanges

Tags:

angular

Why doesn't the ngOnChanges get trigger when you "writeValue" in a ControlValueAccessor ? I am emitting some events via the registerOnChange but I dont see any action in the ngOnChanges

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {
    useExisting: forwardRef(() => CustomInput),
    multi: true
  });

@Component({
  moduleId: module.id,
  selector: 'custom-input',
  templateUrl: 'custom-input.html',
  styleUrls: ['custom-input.css'],
  directives: [CORE_DIRECTIVES],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomInput implements ControlValueAccessor{

  private _text: any = '';
  public isValid:boolean = false;


  onChange: EventEmitter<any> = new EventEmitter();
  onTouched: any;


  constructor(private ngControl:NgControl) {

  }

  ngOnChanges(e) {
    console.log('ngOnChanges');
  }

  get text(): any { return this._text; };

  set text(v: any) {
    if (v !== this._text) {
      this._text = v;
      this.onChange.emit(v);
    }
  }

  writeValue(v) {
    this.text = v;
  }
  registerOnChange(fn): void {
    this.onChange.subscribe(fn);
  }
  registerOnTouched(fn): void {
    this.onTouched = fn;
  }

}
like image 658
Brett Avatar asked Oct 31 '22 02:10

Brett


1 Answers

ngOnChanges is called when @Input() properties change.

Suppose your custom input had a text property:

export class CustomInput implements OnChanges {
    @Input() text;

    ngOnChanges() {
        console.log('ngOnChanges');
    }
}

Then ngOnChanges will be called when someVariable changes:

<custom-input [text]="someVariable"></custom-input>

Changes made from within the component do not trigger the callback. ngOnChanges is purely for Inputs.

https://angular.io/guide/lifecycle-hooks#lifecycle-sequence


Note: ngOnChanges is also called before ngOnInit

like image 135
hayden Avatar answered Nov 15 '22 08:11

hayden