I understand that ngOnChanges is fired when a components @Input property from its parent component. But how I can detect if an @Input property is changed within its component. I've not been able to find a good answer to that. Thanks
To do this, You can use the ngOnChanges()
lifecycle method as also mentioned in older answers:
@Input() yourInput: string;
ngOnChanges(changes: SimpleChanges) {
this.doSomething(changes.yourInput.currentValue);
// You can also use yourInput.previousValue and
}
You can define @Input()
on setter methods so that you can take additional actions whenever new values is being set for an attribute.
Here is a sample component that demonstrates this:
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `<h1 (click)="name = 'Bye'">{{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
private _name: string;
get name() {
console.log("Returning name", this._name);
return this._name;
}
@Input()
set name(newName) {
console.log("Setting new name", newName);
this._name = newName;
}
}
This component when used in another component, can be specified somewhat like below:
<hello [name]="'Hi'"></hello>
In aboe example, initial value of Hi
was set from external/parent component, and on click of text, value is updated to Bye
internal to component. In both cases, you will observe the console.log
statement in browser console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With