Вы можете просто go реагировать. Возьмите экземпляр MatSelectionList
с помощью ViewChild
:
@ViewChild(MatSelectionList, { static: true }) matSelectionOptionsComponentRef: MatSelectionList;
... и выполните вычисления / назначьте наблюдаемые, прослушивая EventEmitter
из ит.
TS :
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-selector',
styleUrls: ['./app-selector.css'],
templateUrl: './app-selector.html'
})
export class AppSelectorComponent {
@ViewChild(MatSelectionList, { static: true })
readonly matSelectionOptionsComponentRef: MatSelectionList;
readonly options: readonly Options[] = [
{ name: 'Item 1', price: 4000 },
{ name: 'Item 2', price: 8000 },
{ name: 'Item 3', price: 3500 },
{ name: 'Item 4', price: 50 }
];
hasDiscount$: Observable<boolean>;
sum$: Observable<number>;
ngOnInit(): void {
this.sum$ = this.matSelectionOptionsComponentRef.selectionChange.pipe(
map(({ source }) => {
return source.selectedOptions.selected
.map(({ value }) => value)
.reduce((previousValue, currentValue) => {
return previousValue + currentValue;
}, 0);
}),
startWith(0)
);
this.hasDiscount$ = this.sum$.pipe(
map(value => value > 10000), // PUT THE CORRECT VALUE HERE
startWith(false)
);
}
}
HTML:
<mat-selection-list>
<mat-list-option class="selected" *ngFor="let option of options" [value]="option.price">
{{ option.name }} - ${{ option.price }}
</mat-list-option>
</mat-selection-list>
<p>You have selected {{ matSelectionOptionsComponentRef.selectedOptions.selected.length }}
items with total sum of ${{ sum$ | async }}.</p>
<p *ngIf="hasDiscount$ | async">Your discount is 10%.</p>
DEMO