You should use the changed event of the SelectionModel API which returns a SelectionChange event emitted when the selection is changed, instead of the selected variable of the SelectionModel API.
The SelectionChange interface has the following properties (taken from the source code):
/**
* Event emitted when the value of a MatSelectionModel has changed.
* @docs-private
*/
export interface SelectionChange<T> {
/** Model that dispatched the event. */
source: SelectionModel<T>;
/** Options that were added to the model. */
added: T[];
/** Options that were removed from the model. */
removed: T[];
}
You can then add or remove the weight from the totalWeight property as follows:
totalWeight = 0;
ngOnInit(): void{
this.selection.changed.subscribe(change => {
console.log('Added items:', change.added);
console.log('Removed items:', change.removed);
console.log('Source selection model:', change.source);
change.added.forEach(element => {
this.totalWeight += element.weight;
})
change.removed.forEach(element => {
this.totalWeight -= element.weight;
})
});
}
Updated demo
changedevent such that that portion of your code will be executed each time the selection is modified.