1 min readFeb 20, 2018
--
ngOnChanges
only runs when the Input
change comes from a template binding like <component [someInput]="aValue">
. If you set it manually like this component.someInput = aValue
, that happens outside the change detection cycle and you need to let Angular know somehow that you’ve changed something.
There are a couple ways to resolve this.
- Directly make the changes that
ngOnChanges
would do. (This is what theupdate
function does in the example.) - Manually trigger change detection.
constructor(private cd: ChangeDetectorRef) {}public someFn() {
this.someInput = aValue;
this.cd.detectChanges();
// ngOnChanges will be called
}
3. Use a getter/setter and don’t worry about ngOnChanges
.
private _aValue;
public get aValue() { return this._aValue; }
public set aValue(newValue) {
// logic
this._aValue = newValue;
}