It is recommended to utilize the changed
event within the SelectionModel
API, which triggers a SelectionChange
event when the selection undergoes changes, instead of relying on the selected
variable from the same API.
The SelectionChange
interface consists of the following properties (extracted from the source code):
/**
* Event triggered when the value of a MatSelectionModel has been altered.
* @docs-private
*/
export interface SelectionChange<T> {
/** The model that initiated the event. */
source: SelectionModel<T>;
/** Items that were added to the model. */
added: T[];
/** Items that were removed from the model. */
removed: T[];
}
Subsequently, you can adjust the weight in the totalWeight
property by either adding or removing it using the following method:
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;
})
});
}
View updated demonstration