Clear out chosen elements from Angular Material's mat-selection-list

Looking for a way to delete selected items from an Angular Material list, I attempted to subtract the array of selected items from the initial array (uncertain if this is the correct approach).

The challenge I face is figuring out how to pass the array of selected items from HTML to TS to manipulate it.

In the Angular Material documentation, there's an example:

{{x.selectedOptions.selected.y}}

Here, x represents the ID of the mat-selection-list selector and y denotes the action with the selected elements. However, this syntax appears to only work in HTML.

Below is the code snippet that is not functioning as intended.

In the HTML section where the list and deletion function triggering button are defined:

<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>

Attempting to interact with the selected options in the TS file leads to errors since selectedOptions is declared as an array of strings and does not have the "selected" method. Despite realizing the mistake, I haven't found a better alternative :) There must be a way to transfer selected elements 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 aim is to update the appList upon clicking the button, removing the selected elements so they no longer appear in the list.

Answer №1

Sharing my solution for others who may encounter a similar issue, here is the code that successfully removed selected elements from the list upon click.

The HTML structure remains unchanged.

TypeScript code snippet:

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 {
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a radio button is clicked in Angular7 and it shares the same form control name, both radio buttons are being

Visit this StackBlitz link for more information. places = ['effil tower','new discover'] new FormGroup({place: new FormControl()}); <div *ngIf="places?.length > 0" class="col-12"> <div style=" padding-top: 1e ...

Centered Fixed Upward Scrolling Div

Currently facing a challenge with my project involving a chat interface created in Angular. I am struggling with the CSS styling as the chat starts at the top and scrolls downward off-screen as the conversation progresses. Although I can scroll along with ...

Issue occurs where the system is unable to recognize a defined variable, despite it being clearly defined

I keep encountering an error message stating that my variable is not defined, even though I have clearly defined it just a few lines above where the error occurs. The reason behind this error is baffling to me, as I cannot identify any potential triggers ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

Guide on creating a dash-patterned line over a rectangle using PixiJS and Angular

https://i.sstatic.net/uIksi.jpg In this example, we are creating a PixiJS application that draws a solid-stroked rectangle. Unfortunately, PIXI.Graphics does not have a built-in feature to draw dashed strokes. import { Component, OnInit } from &ap ...

Error TS2307 - Module 'lodash' not found during build process

Latest Update I must apologize for the confusion in my previous explanation of the issue. The errors I encountered were not during the compilation of the Angular application via Gulp, but rather in the Visual Studio 'Errors List'. Fortunately, I ...

How can I best declare a reactive variable without a value in Vue 3 using TypeScript?

Is there a way to initialize a reactive variable without assigning it a value initially? After trying various methods, I found that using null as the initial value doesn't seem to work: const workspaceReact = reactive(null) // incorrect! Cannot pass n ...

What methods can I use to guarantee that a cloned HTML element retains a specific property during Unit Testing?

During my HTML cloning process, I am using the following code snippet: var clone = document.getElementById('tempID').cloneNode(true); After creating the clone, I need to modify its ID by assigning a new unique identifier with clone['id&apo ...

Dynamic routing with ngIf in Angular 2's router system

Is there a way to use *ngIf with dynamic router in Angular? Let's say I have a top navigation component with a back button, and I only want the back button to be visible on the route 'item/:id'. I tried using *ngIf="router.url == '/ite ...

How can we regularly retrieve data in Angular 5 using Observables, while also incorporating instant fetching with RxJs 5.x?

Currently, I am in the process of developing a Single Page Application using Angular 5. One of the requirements is to periodically check if the API version matches the one loaded when the SPA was initialized. This check is essential to inform the user abou ...

"Revolutionize your date and time selection with the dynamically updating columns

I am in need of a time selection feature where users can choose both hours and minutes. Each hour will have its own set of minutes, and the data structure should look like this: [ { hour: 1, minutes: [0, 15, 30], }, { hour: 4, minut ...

Utilizing indexes to incorporate elements into an object array

I'm currently working on a project using Angular. I have an index coming from the HTML, and here is the code snippet: save(index){ //this method will be called on click of save button } In my component, I have an array structured like this: data = [{ ...

Steps for sending angular form data to a .Net backend that requires an autoincrement id:

When trying to insert data into an SQL database through a .Net API endpoint, I encountered an issue with the request body specifying that the ID is auto-incremental. Status 500: Cannot insert explicit value for identity column in table 'StockFeed&ap ...

Error in Angular Services due to Circular Dependency

I am encountering the following error message: Provider parse errors: Cannot instantiate cyclic dependency! Within my code, I have a Component dedicated to making HTTP calls to my backend server: backend.component.ts import { Http } from '@angul ...

Is seamless integration possible between Angular2 and jQuery plugins?

When attempting to integrate jQuery plugins with Angular 2, there are three distinct scenarios: 1. ONLOAD: Initializing the plugin on page load works smoothly with the following code snippet: ngAfterViewChecked(){ ... $('#somedatatable1&apos ...

Angular class mapping of web API response

I have a web API action method that returns a chapter ID and chapter name. I would like to convert this into an Angular class with an additional field called 'Edit', which by default is set to false. export class Chapter { chapterid: number; ...

What is the best way to showcase several images using Sweet Alert 2?

In the process of developing my Angular 2 application, I have incorporated sweet alert 2 into certain sections. I am looking to showcase multiple images (a minimum of two) at the same time in the pop-up. Does anyone have any suggestions on how to achieve ...

What is the proper method for transferring a JWT token to an external URL?

I currently have two REST endpoints set up: accounts.mydomain.com/login - This is an identity provider that sends a JWT token as a response once a user is authenticated with their username and password. api.mydomain.com/users - This endpoint accepts the ...

Issues with setting default values for controls in Angular's reactive forms

I need help with displaying a preselected option on my dropdown list. I have set the value to preSelectedLegalType in the ngOnInit function, but for some reason it is not getting displayed. How can I make sure this value is displayed? The TypeScript file ...

In a specific Angular project, the forget password feature is experiencing issues with sending email links in the Chrome browser. Interestingly, this issue only occurs the first

I'm currently working on an Angular 6 application that has been deployed with the domain "www.mydomain.com/". All the routes are functioning properly, such as "www.mydomain.com/dashboard" and "www.mydomain.com/products". However, there is an issue w ...