Tips for Programmatically Choosing a Single Value Option in Angular

I have implemented a "Select All" feature in my select list to clear all other selected options and only choose the "All" option. However, I am facing an issue where I can clear out all selected options but cannot select the "All" option.

<mat-form-field class="example-full-width">
   <mat-label>Select Program(s)</mat-label>
   <mat-select #myprograms  [formControl]="myprgrmFormControl" multiple [(ngModel)]="criteria.Program_ID" >
       <mat-option (click)="toggleAllSelection()" value="ALL" >All</mat-option>
       <mat-option *ngFor="let row of ProgramDropdown"  [value]="row.Program_ID" >
            {{row.Program_Name}} </mat-option>
   </mat-select>
</mat-form-field>

In the typescript file:

import { MatSelect } from '@angular/material/select';
import { MatOption } from '@angular/material/core';

myprgrmFormControl = new FormControl();
allSelected = false;
@ViewChild('myprograms') ProgSel: MatSelect;

toggleAllSelection() {
    this.allSelected = !this.allSelected;  
    if (this.allSelected) {
       this.ProgSel.options.forEach( (item : MatOption) => item.deselect());
     } else {
       this.ProgSel.options.forEach( (item : MatOption) => {item.deselect()});
     }
}

How can I select the "All" option programmatically in the typescript file?

Answer №1

Here are the necessary steps to achieve this task:

  1. If you are utilizing objects as your choices in the mat-option, make sure to implement a compareWith function in your mat-select. Also, update the [(ngModel)] and mat-option [value] binding at the object level.
  2. Create an allOption with a structure that aligns correctly with your new compareWith function for accurate evaluation.
  3. Use setValue() programmatically on myprgrmFormControl with an array containing the new allOption. Remember to update your value binding: [value]="allOption"

html:

<mat-form-field class="example-full-width">
   <mat-label>Select Program(s)</mat-label>
   <mat-select #myprograms  [formControl]="myprgrmFormControl" multiple [(ngModel)]="criteria" [compareWith]="selectCompare">
       <mat-option (click)="toggleAllSelection()" [value]="allOption" >All</mat-option>
       <mat-option *ngFor="let row of ProgramDropdown"  [value]="row" >
            {{row.Program_Name}} </mat-option>
   </mat-select>
</mat-form-field>

ts:

  allOption = { Program_ID: 'ALL', Program_Name: 'ALL' };

  toggleAllSelection() {
    this.allSelected = !this.allSelected; // to control select-unselect
    if (this.allSelected) {
      this.ProgSel.options.forEach((item: MatOption) => item.deselect());
      this.myprgrmFormControl.setValue([this.allOption]);
    } else {
      this.ProgSel.options.forEach((item: MatOption) => {
        item.deselect();
      });
    }
  }

  selectCompare(item1: SelectType, item2: SelectType) {
    return item1.Program_ID === item2.Program_ID;
  }

https://stackblitz.com/edit/angular-tqu7nc?file=src%2Fapp%2Fselect-multiple-example.html

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

What could be causing my code to not run after subscribing to the observables?

In my code, I have two methods that return two lists: one for accepted users and the other for favorite users. The first part of my code works well and returns both lists, but in the second part, I need to filter out the accepted users who are also on the ...

Guide to presenting fields on a distinct line or section in Angular 7 forms

I would like to arrange the username area and password area on separate lines with spaces in between. Here is the HTML code snippet: This HTML code is for a login angular GUI. <mat-card class="card"> <mat-card-content> <!-- CONT ...

Using Angular 4's ngModel can result in the transformation of data type from 'number' to 'string'

I am facing an issue with my Angular4 app where data captured from a form is stored in DynamoDB. The problem arises when an input field typed as 'text' is bound to a Typescript 'number' field, which seems to be converting the object val ...

Automatically focus on the button

Encountering an issue where setting focus on a button upon the input key enter event is not working. While setting focus on inputs functions properly, using the same code on a button does not work at all. Sample HTML Component: <form [formGroup]=&apos ...

Utilize an enum to serve as a blueprint for generating a fresh object?

I've defined an enum as shown below: export enum TableViewTypes { user = 'users', pitching = 'pitching', milestones = 'milestones', mediaList = 'mediaList', contacts = 'contacts' } ...

Angular 11 component encountering issues with accessing server-side data

Recently, I encountered an issue when trying to connect the PHP API with the Angular service to retrieve data from the database. I am uncertain whether the problem lies within the service, the component.ts file, or the HTML section. Therefore, I have share ...

There seems to be an issue with calling this particular expression. The elements within the type 'string | ((searchTerm: string) => Promise<void>) | []' are not all callable

Here is my unique useResults custom hook: import { useEffect, useState } from 'react'; import yelp from '../api/yelp'; export default () => { const [results, setResults] = useState([]); const [errorMessage, setErrorMessage] = us ...

Tips for utilizing canReuse and routerOnReuse in Angular 2

I've reviewed the information provided in this link, but I'm still unsure about how to effectively utilize it. My requirement is straightforward—I need to update a parameter in the URL without constantly sending API requests, which are current ...

Can we create an intersection type of Records by pairing keys with tuples or unions of values in a one-to-one correspondence?

If I have tuples similar to this for keys and values: type Keys = ['North', 'East', 'South', 'West']; type Values = ['n', 'e', 's', 'w']; Is there a way to achieve a structure ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

Using Angular's filter pipe to search within a nested array

We are attempting to implement an angular pipe for filtering a list of sub-items, with the goal of removing parent items if there are no child items present. Here is the HTML code snippet we are using: <div class="row border-bottom item" *n ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

transmit URL parameters to Express using Angular 2

I have implemented an Angular service to retrieve data from Express: getRestaurants(districtId) : Observable<void[]>{ let params: URLSearchParams = new URLSearchParams(); params.set('id', districtId); return this.http.get(this.url, ...

Transforming JSON keys in Angular

As a newcomer to angular and API integration, I am facing an issue with ngCharts in my project. The chart specifically requires the keys names in JSON to be "value" and "name", but the API I am using provides keys named "count" and "label". Is there a way ...

Models in Typescript that are interrelated with Loopback

I'm currently working on defining connected models including the HasMany relationship in the context of @types/loopback definitions My approach involves creating an interface for HasMany and its implementation: interface IHasMany { /** ...

The insecure connection to http://bs-local.com:3000 has prevented access to geolocation

Hi everyone, I hope your day is going well. I could really use some assistance with an issue I've run into. I'm currently trying to test my React web app on BrowserStack's mobile screens, but I am doing the testing locally using localhost. ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

Similar to the "beforesend" functionality in JavaScript, there is a corresponding feature

When attempting to post a comment in my ionic app using the Wordpress api, I encountered error 401 (unauthorized) indicating that the Wordpress api does not recognize me as logged in. This is the code I am using: postComment(params?: any) { let nonce = l ...