Reputation: 381
Is there a way to get simple changes on a QueryList? I have a list of childcomponents which I hold in a querylist. I want to check which childcomponent has been added to the list (in an onchange event).
Parentcomponent:
@ContentChildren(forwardRef(() => ChildComponent), { descendants: true })
private childComponents: QueryList<ChildComponent>;
When I click on a button a childcomponent gets added to the dom so the querylist changes triggers.
When I subscribe to the querylist like so:
this.childComponents.changes.subscribe((changes) => {
//here i just get the updated list. I don't have the previous list to compare.
});
Upvotes: 1
Views: 2198
Reputation: 12596
a list QueryList
has changes
event, you could subscribe to it. then you could using IterableDiffers
for compare
Parentcomponent:
@ContentChildren(forwardRef(() => ChildComponent), { descendants: true })
private childComponents: QueryList<ChildComponent>;
constructor(private differs: IterableDiffers) {
this.differ = this.differs.find([]).create(null);
}
// in some method
this.childComponents.changes.subscribe((changes) => {
let changeDiff = this.differ.diff(changes);
if (changeDiff) {
changeDiff.forEachAddedItem((change) => { // added item
});
changeDiff.forEachRemovedItem((change) => { // removed item
});
}
});
Online Demo for sample accordion: https://plnkr.co/edit/1xNOvp?p=preview
Open your console to see result
https://angular.io/docs/ts/latest/api/core/index/IterableDiffers-class.html
Upvotes: 2