How can you load a chosen list in Angular's Mat Selection List component?

I populated my selection list with a list of items. How can I specify which item should be selected in the list after it has been loaded?

Here is the HTML code snippet:

<div class="col-md">
    <div class="form-group">
      <label>Sub Issue Listbox</label>
      <mat-selection-list
        #IssueList
        style="max-height: 250px; overflow: auto"
        formControlName="issueId">
        <mat-list-option
          *ngFor="let item of subIssueList"
          [value]="item.issueId">
          {{ item.issueDesc }}
        </mat-list-option>
      </mat-selection-list>
      <p>
        Options Selected:
        {{ IssueList.selectedOptions.selected.length }}
      </p>
      <button
        (click)="updateOqcReject()"
        mat-raised-button
        color="accent">
        Update Issue
      </button>
    </div>
</div>

This is the array for the loaded list.

https://i.sstatic.net/HTtYA.png

And this is the array for the selected list. https://i.sstatic.net/Ct0wb.png

If anyone could provide guidance on how to set the selected value in the list, that would be greatly appreciated.

Answer №1

To populate your control, utilize the setValue function along with the issueId

Make sure to call this method after loading your list.

For instance:

this.form.get('issueId').setValue(selectedValue);

In this case, selectedValue should represent the desired issueId to be selected

Answer №2

To utilize the MatSelectionList, you can query it and make use of the [selected] input within the mat-selection-list

@Component({
  selector: 'list-selection-example',
  styleUrls: ['list-selection-example.css'],
  templateUrl: 'list-selection-example.html',
})
export class ListSelectionExample {
  typesOfShoes: any[] = [{id: 0, title: 'Boots'}, {id: 1, title: 'Clogs'}, {id: 2, title: 'Loafers'}, {id: 3, title: 'Moccasins'}, {id: 4, title: 'Sneakers'}];

  @ViewChild(MatSelectionList) list: MatSelectionList;

  ngAfterViewInit() {
    const mySelections = [{id: 1, title: 'Boots'}]
    /* Select your selections into MatSelectionList */
    mySelections.map((s) => this.list.selectedOptions.select(s.id as any))
  }
}

Additionally, in the html file:

<mat-selection-list #shoes>
  <mat-list-option
    [selected]="shoes.selectedOptions.isSelected(shoe.id)"
    [value]="shoe.id"
    *ngFor="let shoe of typesOfShoes"
  >
    {{shoe.title}}
  </mat-list-option>
</mat-selection-list>

<p>Options selected: {{shoes.selectedOptions.selected.length}}</p>

Feel free to try out the functionality on Stackblitz

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

Enhancing User Experience through 'Remember Me' Feature in Angular App

I need assistance with adding the Remember Me functionality to a login form in an Angular application. Could someone please provide guidance on how to achieve this? Your help would be highly appreciated! Thank you in advance! Below is my login.ts file: ngO ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

When implementing useReducer with TypeScript, the error "Argument of type '(type, action) => { state: (...}' is not assignable to parameter of type 'ReducerWithoutAction<any>'" may occur

Recently, I decided to delve into learning TypeScript by building a simple shopping cart application. If you want to check out the code, feel free to visit my GitHub repository: https://github.com/CsarGomez/shopping-cart-reducers-tx I've encountered ...

Unable to set up ng-bootstap on Angular version 16.1.3

Upon attempting to integrate ng-bootstrap with Angular 16.1.3, an error was encountered during installation: Would you like to proceed? Yes npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l ...

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

Achieving selective exclusion of specific keys/values while iterating through an array and rendering them on a table using Angular

Currently facing a hurdle and seeking advice I am developing an angular application that fetches data from an API and presents it on the page The service I am utilizing is named "Api Service" which uses HTTPClient to make API calls apiservice.service.ts ...

What is the significance of utilizing the "$event" keyword for event binding in Angular? (for the end result)

Check out this code snippet (taken from here): Main component: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', template: `<app-child (valueChange)='displayCounter($event)'> ...

The pagination, sorting, and filtering features in my Angular Material project seem to be malfunctioning

Having created a project on Angular CLI 7, I decided to incorporate Angular Material into it. Despite adding modules for table pagination, expansion, filter, and sort in the app modules file, I am facing difficulties making the paginator, sorting, and fil ...

"Element of design focused on style and arrangement

After reviewing the material ui documentation located at https://material-ui.com/components/typography/ I attempted to utilize the Typography component in the following manner: <Typography variant="h1" component="h1"> Hello World </Typography& ...

Contrast between SimpleChange and SimpleChanges

I'm confused about the two terms in Angular 5, SimpleChange and SimpleChanges. Can someone please help explain them to me more clearly than what's in the official documentation? ...

Modify the disabled background color of the mat-form-field component in Angular version 15

Is there a way to customize the background color and outline of disabled text input in Angular 15? I attempted using mdc-text-field--disabled and overriding the outline CSS, but it had no effect. Current appearance when disabled https://i.sstatic.net/Ogu ...

Ways to retrieve sorted and updated items in ngx-datatable post-sorting

I am currently utilizing the swimlane/ngx-datatable library to display a list. Within each row of the list, I have implemented an action menu that pops up upon clicking an icon, with dynamically generated items. Challenge: Following sorting, the items app ...

Dealing with 400 Bad Request Error Handling in Angular 6 when communicating with WebApi (using HttpClient)

Here is an Asp.net Core WebAPI that handles bad requests by providing error details when a duplicate user attempts to register. public async Task<IActionResult> Register([FromBody] RegisterModel registerModel) { if (ModelState.IsValid) ...

The MemoizedSelector cannot be assigned to a parameter of type 'string'

Currently, my setup involves Angular 6 and NgRX 6. The reducer implementation I have resembles the following - export interface IFlexBenefitTemplateState { original: IFlexBenefitTemplate; changes: IFlexBenefitTemplate; count: number; loading: boo ...

"Customize the appearance of ng-bootstrap datepicker selection with a unique

Having trouble with the ng-bootstrap datepicker when selecting style for month and year. https://i.sstatic.net/grlK6.png The issue seems to be with the select style. select[_ngcontent-c21] { -ms-flex: 1 1 auto; flex: 1 1 auto; padding: 0 .5re ...

Testing Angular components using ViewChild and directives

I've created a Plunker that showcases the issue I'm facing: https://embed.plnkr.co/UparfJDomOECGJfWSbqA/ In short, I'm having trouble testing my component as it appears to be failing in container.component.spec.ts:43. However, if I don' ...

tsconfig.json: No input files were detected in the configuration file

I am encountering an issue with my tsconfig.ts file where it says "No inputs were found in config file 'd:/self-study/Web/Learning/Express/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude&a ...

Preserve Inference in Typescript Generics When Typing Objects

When utilizing a generic type with default arguments, an issue arises where the inference benefit is lost if the variable is declared with the generic type. Consider the following types: type Attributes = Record<string, any>; type Model<TAttribu ...

What is the best way to ensure that a div containing lengthy text wraps to the next line as if it were only text overflow?

Is there a way to make a div or span within another div act as text, causing overflow to shift to the next line? I'm unsure of which CSS properties would achieve this effect. I've attempted using overflow-wrap: break-word; word-break: break-al ...

Multiple invocations of the callback function in an Angular5 template binding

In trying to create a grid component that uses structured data containing definitions for columns and an array of data. Each column definition includes a callback function to customize the display of that specific column's value. Within each callbac ...