0

I have an @Input that does something when it's true ngOnChange doesn't detect when it's false

@Input() viewMode: boolean;

  ngOnChanges(changes: SimpleChanges) {
    if (changes.viewMode.currentValue !== undefined) {    
      if (changes.viewMode.currentValue ) {
        this.populateForm(this._event);
      }else{
        this.doSomething()
      }
    }
  }


setValue(){

   this.viewMode = false; 
}

When I call the setValue function it doesn't fall into ngOnChange

user3140824
  • 338
  • 5
  • 25

2 Answers2

1

I had this doubt myself also few days back. And what I found out is - ngOnChanges does not fire this way. ngOnChanges only runs when input of component changes from outside. i.e. Suppose you have,

<app-selector [editMode]="true"></app-selector>

And this changes to,

<app-selector [editMode]="false"></app-selector>

Now only angular will run ngOnchanges. If you want to do something whenever the property of this variable changes, you should use the setter and getter for this variable like so,


private _viewMode: boolean;

@Input() set viewMode(mode) {
  this._viewMode = mode;
  this.populateForm(this._event);
}

get viewMode() {
  return this._viewMode;
}

Now you can call your function like this.setValue() and your form will populate everytime.

Archit Garg
  • 2,908
  • 2
  • 14
  • 22
0

ngOnChanges only runs when the Input change comes from a template binding like <component [someInput]="value">. If you set it manually like this component.someInput = value, that happens outside the change detection cycle and you need to let Angular know somehow that you’ve changed something.

if you still want the ngOnChanges to be triggered, you will have to do it manually. i.e.


constructor(private cd: ChangeDetectorRef) {}

setValue(){
  this.viewMode = false; 
  this.cd.detectChanges();
}

Hope it helps and clarifies your doubt!

Ganesh Krishna
  • 714
  • 1
  • 7
  • 13