Reputation: 4756
I nmy subcomponent, I have an input called "data"
@Input() data: Array<any> = [];
I take a copy of this variable when my component is initiated
ngOnInit() {
this.dataCopy = _.cloneDeep(this.data)
}
In my main component it can happen that I need to add something to this data variable.
Main Comp:
// this.nextStatusesToSelect = data for subcomponent
let dataIndex = this.nextStatusesToSelect.findIndex(i => i.ID === e.ID);
if (dataIndex === -1) {
this.nextStatusesToSelect.push(e);
}
I can see that in my subcomponent my data
variable gets correctly updated, however this means I also need to update the copy.
How can I trigger a function in my subcomponent when my
data
variable changes?
I've been reading about usingOnChanges
however this doesn't seem to work for me at all since it doesn't get triggerd.
ngOnChanges(changes) {
console.log(changes);
}
Upvotes: 0
Views: 373
Reputation: 632
Instead of:
this.nextStatusesToSelect.push(e)
try this
this.nextStatusesToSelect = [...this.nextStatusesToSelect, e]
This should trigger a change in your ngOnChanges()
method.
This article also might be helpful in finding the best way of what are you trying to achieve and shows advantages of Immutable approach in Angular.
Upvotes: 1