Angular 4 - Custom two way binding

Viewed 2969

I am trying to implement a custom two way binding between two of my components.

I did read about the naming convention saying that you have to define a @Input() like "test" and then define a @Output() named "testChange".

I couldn't find anything about whether this is still up-to-date or not and I can't get my binding to work.

Some code within parentComponent:

<my-comp [(userGroupIds)]="userGroups"></my-comp>

MyComponent (child):

export class MyComponent implements OnInit, OnDestroy{
  @Input() userGroupIds: number[];
  @Output() userGroupIdsChange = new EventEmitter<number[]>();

  updateValues(){
    //here I am iterating through the rows of a table within my component
    this.userGroupIds = this.tableRows.map(item => {return item['id']});
    this.userGroupdIdsChange.emit(this.userGroupIds);
  }
}

parentComponent:

export class parentComponent implements OnInit, OnChanges, OnDestry{
  userGroups: number[];
  constructor(){
    this.userGroups = [];
  }

  ngOnChanges(changes: SimpleChanges){
    if(changes['userGroups']){
      // this is never show, ngOnChanges doesn't get fired;
      console.log(this.userGroups);
    }
  }
}

Is there something I am missing? Did the Angular-Team change anything?

Afaik the binding does something like

[userGroupsIds]="userGroups" (userGroupsIdsChange)="userGroupIds=$event"

So I tried setting this myself, but no update either. Only thing that work was passing a function to the eventEmitter.

1 Answers

Your binding works like a charm, it does not trigger the ngOnchanges method, which is the expected behavior.

from the Angular docs :

OnChanges

Lifecycle hook that is called when any data-bound property of a directive changes.

as userGroups is not an @Input() it cannot be a "data-bound property" , its value changing internally will not run the ngOnChanges hook.

Related