2
votes

I need to be able to remove selected items from an Angular Material list. To do so, I decided to subtract the array of selected items from the initial array of items (not sure this is the best way to do it).

My problem is that I can't find a way to pass the array of selected items from HTML to TS and play with it.

Angular Material has the following example in their documentation:

{{x.selectedOptions.selected.y}}

where x is the ID of the mat-selection-list selector and y is something that you do with the selected elements. But this seems to work in HTML only.

Below there's my code which doesn't work.

HTML where I set up the list and the button which should trigger the deletion function.

<mat-selection-list #apps>
    <mat-list-option *ngFor="let app of appList" [value]="app">
      {{app}}
    </mat-list-option>
</mat-selection-list>

<button 
class='remove-button' 
(click)="deleteSelected()"
mat-stroked-button color="primary">
    Remove from list
</button>

TS where I try to mess with the selected options but it obviously doesn't work because selectedOptions is declared as an array of strings and doesn't have the "selected" method. I understand that was a dumb attempt but anyway, can't find any better way:) There should be a way to pass selected elemets as an array to TS...

export class SubscriptionListComponent implements OnInit {

  selectedOptions: string[]
  appList: string[] = ['Instagram', 'Facebook', 'Telegram', 'WhatsApp', 'GitHub']

  deleteSelected() {
    this.appList.filter(x => !this.selectedOptions.selected.includes(x))
  }

The goal is to modify the appList on click on the button so the selected elements are removed from it and don't show up in the list as well.

1
selectedOptions is a property of MatSelectionList. See if you can reference it with @ViewChild(MatSelectionList) selectionList: MatSelectionList;robbieAreBest
@robbieAreBest thank you, much appreciated, it perfectly worked!Pirunpoika

1 Answers

1
votes

For those who might face the same challenge, I post the code which worked for me and did exactly what I wanted (remove selected elements from the list on click).

HTML stayed the same as above.

TS:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSelectionList } from '@angular/material/list';


@Component({
  selector: 'app-subscription-list',
  templateUrl: './subscription-list.component.html',
  styleUrls: ['./subscription-list.component.scss']
})
export class SubscriptionListComponent implements OnInit {

  @ViewChild('apps') selectionList: MatSelectionList

  appList: string[] = ['Instagram', 'Facebook', 'Telegram', 'WhatsApp', 'GitHub']

  deleteSelected() {
    var selected: string[] = this.selectionList.selectedOptions.selected.map(s => s.value)
    var diff = this.appList.filter(el => !selected.includes(el))
    this.appList = diff
  }

  constructor() { }

  ngOnInit(): void {
  }

}