javascriptangulareventemittertwo-way-bindingcontrolvalueaccessor

Angular Two-Way Data Binding and Watching for Changes in Parent Component


It seems there is no way to watch changes in the parent component when using two-way data binding.

I have a custom input component for collecting a tag list. Two-way data binding is setup and working between this component and its parent.

// the parent component is just a form
// here is how I'm adding the child component
<input-tags formControlName="skillField" [(tags)]='skillTags' (ngModelChange)="skillTagUpdate($event)">
</input-tags>

In the parent component how do you watch the bound variable for changes? While it's always up to date (I've confirmed this) I cannot find any guidance on reacting to changes.

I've tried:

ngOnChanges(changes: SimpleChanges) {
    if (changes['skillTags']) {
        console.log(this.skillTags);  // nothing
    }
}

And

skillTagUpdate(event){
    console.log(event); // nothing
}

UPDATE: TWDB IMHO is not what it is advertised to be. Whenever I arrive at this place where TWDB seems to be a solution I rearchitect for a service and or observable communication instead.


Solution

  • When you implement a two way binding of your own, you have to implement an event Emitter. The syntax for that is mandatory.

    this means that you have a hook to listen to if the value changes.

    Here is a demo :

    <hello [(name)]="name" (nameChange)="doSomething()"></hello>
    
    _name: string;
    @Output() nameChange = new EventEmitter();
    
    set name(val) {
      this._name = val;
      this.nameChange.emit(this._name);
    }
    
    @Input()
    get name() {
      return this._name;
    }
    
    counter = 0;
    
    ngOnInit() {
      setInterval(() => {
        this.name = this.name + ', ' + this.counter++;
      }, 1000);
    }
    

    Stackblitz

    From what I know, this seems the less annoying way to use it, and any two way binding will follow the same rule no matter what, i.e. it ends with the Change word !