4

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.

2
  • 2
    ngOnChanges only fires if any of @Input's has changed. I don't see any @Input's in your parent component. And change should come from parent component(parent of your parentComponent) Commented Sep 28, 2017 at 9:09
  • You have a typo - extra d in userGroupdIdsChange Commented Sep 28, 2017 at 9:12

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh dear, I really feel stupid right now. I wasn't even close on thinking about ngOnChanges being the "problem" here. Thank you! Works like a charm indeed. edit: Is there something other that would do what I expected OnChanges to do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.