Dirk Dirk - 3 months ago 38
TypeScript Question

Angular 2: ngOnChanges fires when template renders

When my template renders the function inside ngOnChanges fires one time, and then only when an @input changes. Is this the expected behaviour and how can I prevent it?

Child:

export class MobileMenuComponent implements OnInit, OnChanges {

@Input('test') dezeTest: string;

//declare menu
menu;

constructor() {

//define menu

this.menu = {state: 'inactive'};

}

togglemenu() {

var that = this;

if (that.menu.state === 'inactive'){

that.menu.state = 'active';

}

else {

that.menu.state = 'inactive';

}

}

ngOnChanges(changes: SimpleChanges) {


this.togglemenu();


}
}

Answer

This is the normal behaviour of ngOnChanges.

The ngOnChanges method will fire the first time because your properties have been checked, and subsequently fire when a property is updated. From the documentation, you can see

ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed.

If you want to change it, you need to consider how you want to change it. That is not very clear from your question, but if you want to prevent the ngOnChanges from firing again, when a property is updated (I think that you want this because of your toggleMenu() you might consider using the ngOnInit() instead of ngOnChanges(). Alternatively, you can block the togglemenu(); after the first time.

 firstrun : boolean = true; // class variable
 ngOnChanges(changes : SimpleChanges){
    if(firstrun){
      this.togglemenu();
      firstrun = false;
    }
  }

Alternatively, as hinted at earlier, another lifecycle hook might suit your needs better.

Comments