Angular2: Input setter not picking up set event if value does not change
Not positive if using the input setter is a strict requirement, but have you tried using OnChanges?
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'name-child',
template: '<h3>"{{name}}"</h3>'
})
export class NameChildComponent implements OnChanges {
@Input() name;
ngOnChanges(changes: SimpleChanges) {
if (changes['name']) {
console.log(`Is First Change: ${changes['name'].isFirstChange}`)
console.log(`name change from ${changes['name'].previousValue} to ${changes['name'].currentValue}`);
}
}
}
I see two ways to solve it:
1) Use immutable value
setTimeout(() => {
this.name = new String("a");
setTimeout(() => {
this.name = new String("a");
setTimeout(() => {
this.name = new String("a");
}, 1000);
}, 1000);
}, 1000);
2) Change input property directly
@ViewChild(NameChildComponent) child: NameChildComponent;
setTimeout(() => {
this.child.name = "a";
setTimeout(() => {
this.child.name = "a";
setTimeout(() => {
this.child.name = "a";
}, 1000);
}, 1000);
}, 1000);
The article you give explicitly says
Intercept input property changes with a setter
when what you are trying to achieve is not about tracking changes at all. It is about sending an event from parent to child and this is where RX Subject
(any of 4 of them) or Angular2 EventEmitter
is really good.
You can create one of them in the parent and pass it to the child. Then, after you subscribe to it, you can track all the events regardless of the value.