No data is generated when choosing from the dropdown menu in mat-select

I have a select function where all options are selected, but the selected sections are not shown. When I remove the all select function, everything works fine. Can you help me find the error?

Check out my work on Stackblitz

Here is my code:

Select

<mat-select [(value)]="selectedValues" formControlName="dashboardValue" multiple>
   <mat-option class="dashboard-select-option" *ngFor="let dashboardPosition of displayDashboardValues" 
      [value]="dashboardPosition.key" (click)="togglePerOne(allSelected.viewValue)">
      {{ dashboardPosition.viewValue }}
   </mat-option>
   <mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
</mat-select>

Output

<div class="col-md-12" *ngIf="selectedValue['valuePositionType'] === 'profit-loss-area'">
   <app-profit-loss-area></app-profit-loss-area>
</div>
<div class="col-md-12" *ngIf="selectedValue['valuePositionType'] === 'cash-area'">
   <app-cash-area></app-cash-area>
 </div>

TS

 public displayDashboardValues = [
    {key:'1', valuePositionType: 'profit-loss-area', viewValue:'Ergebnis'},
    {key:'2', valuePositionType: 'cash-area', viewValue:'Cash'},
  ]; 

// Dashboard form
    this.dashboardForm = this.formBuilder.group({
      dashboardValue: [null]
    });

// Select options
  togglePerOne(all){
    if (this.allSelected.selected) {
      this.allSelected.deselect();
      return false;
    }
    if(this.dashboardForm.controls.dashboardValue.value.length==this.displayDashboardValues.length)
      this.allSelected.select();
  }

  toggleAllSelection() {
    if (this.allSelected.selected) {
      this.dashboardForm.controls.dashboardValue
        .patchValue([...this.displayDashboardValues.map(item => item.key), 0]);
    } else {
      this.dashboardForm.controls.dashboardValue.patchValue([]);
    }
  }

Answer №1

If you are utilizing dashboardPosition.key as the value, your ngIf condition

selectedValue['valuePositionType'] === 'profit-loss-area'
may not function correctly. This is because only the selected keys are present in your selectedValues list. To observe what happens, try adding {{selectedValues}}. Additionally, there appears to be a copied and pasted fragment in your code: [value]="0".

To address these issues, I recommend implementing the following changes:

Firstly, you can refer to this functional Stackblitz example.

Component

  • Add a dummy entry to your displayDashboardValues array for select all functionality
  • Utilize a boolean variable for allSelected
  • In your method toggleAllSelection, simply set the selectedValues
export class AppComponent implements OnInit  {

  dashboardForm: FormGroup;
  selectedValues: any;
  allSelected = false;

   public displayDashboardValues = [
    {key:'0', valuePositionType: 'undefined', viewValue:'Alle'},
    {key:'1', valuePositionType: 'profit-loss-area', viewValue:'Ergebnis'},
    {key:'2', valuePositionType: 'cash-area', viewValue:'Cash'},
    {key:'3', valuePositionType: 'balance-area', viewValue:'Bilanz'},
    {key:'4', valuePositionType: 'staff-area' ,viewValue:'Mitarbeiter'},
    {key:'5', valuePositionType: 'divisions-area', viewValue:'Sparten'},
    {key:'6', valuePositionType: 'commisions-area', viewValue:'Aufträge'},    
  ];

  constructor(private formBuilder: FormBuilder) {}
  
  ngOnInit() {
     // Dashboard form
    this.dashboardForm = this.formBuilder.group({
      dashboardValue: [null]
    });
  }

  toggleAllSelection() {
      this.allSelected = !this.allSelected;  // to control select-unselect
      this.selectedValues = this.allSelected ? this.displayDashboardValues : [];
    }
}

Template

  • Show mat-option values with key > 0 by default
  • Add another mat-option with a custom value (as previously done) and connect it to your toggleAllSelection method
<mat-select  [(value)]="selectedValues" (selectionChange)="selectionChange($event)" formControlName="dashboardValue" multiple>
          <div *ngFor="let dashboardPosition of displayDashboardValues">
            <mat-option class="dashboard-select-option" *ngIf="dashboardPosition.key>0" [value]="dashboardPosition">
              {{ dashboardPosition.viewValue }}
            </mat-option>
          </div>
          <mat-option [value]="displayDashboardValues[0]" (click)="toggleAllSelection()">{{ displayDashboardValues[0].viewValue }}</mat-option>
        </mat-select>

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

Tips for transferring data when clicking in Angular 5 from the parent component to the child component

I need assistance with passing data from a parent component to a child component in Angular 5. I want the child component to render as a separate page instead of within the parent's template. For example, let's say my child component is called & ...

Tips for injecting scripts into the head tag after an Angular component has been loaded

Currently, I am facing an issue with a script tag containing a Skype web control CDN. The script has been placed in the head section of my index.html file, but it is being called before the component that needs it has finished loading. Does anyone have a ...

Struggling with getting render props to work in Next.js version 13

Looking to develop a custom component for Contentful's next 13 live preview feature in the app directory, I thought of creating a client component that can accept a data prop and ensure type safety by allowing a generic type to be passed down. Here is ...

What is the reasoning behind an empty input value being considered as true?

I am facing an issue with the following code that is supposed to execute oninput if the input matches the answer. However, when dealing with a multiplication problem that equals 0, deleting the answer from the previous calculation (leaving the input empt ...

Overriding the 'first' attribute in PrimeNG's lazy table when implementing filtering

I encountered an issue while attempting to set up a primeNG table using query parameters. For example, when accessing , the data displayed should pertain to "Joe" and start at the 20th entry. To handle the large volume of data my backend can provide, lazy ...

Tips for incorporating nonce or sha into the connect-src directive in Content Security Policy (CSP)

Can a nonce be used in an API request to make sure that the connect-src in CSP doesn't flag it as a malicious address? It appears that nonce can only be used in script-src or style-src, not in connect-src. So far, I have only been able to list URLs ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

Accessing BIM Components: Identifying Global and Express IDs through Selection

As I delve into the task of handpicking specific elements from the intricate web of an IFC model, my approach involves utilizing a SimpleRayCaster to cast a ray onto the object with relative success. The challenge lies in identifying the exact entity inter ...

Exploring the dynamics of parent and child components in Angular

I'm currently working on an Angular2 project and I've hit a roadblock with the parent/child component interaction. My goal is to have a "Producer" entity that can have multiple "Products". Ultimately, I aim to retrieve lists of products associat ...

Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)? The following code partially addresses this issue using the replace method: str = 'Lorem ipsum dolor is amet <a id="2" css ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

Implementing the breadcrumb component within dynamically loaded modules loaded through the router-outlet component

I'm currently working on an angular 8 breadcrumb component for my application. The requirement is to display it in the content of the page, not just in the header, and it should never be located outside the router-outlet. This has posed a challenge fo ...

Child Route Handling Based on Conditions (Angular)

Can a child route be conditionally displayed as a default? I want users to land on a specific child route based on their past orders (e.g., go to the store page if they ordered from a physical store, online page for online orders, or social page otherwise ...

Unable to attach a tooltip to a list item

As an Angular developer, I am working on a list element that displays all the cars and I am looking to add a tooltip to enhance its visual appeal. Here is what I have attempted so far: I created a span tag with the class "tooltip" to wrap around the ul el ...

Utilize Angular2 data binding to assign dynamic IDs

Here is the JavaScript code fragment: this.items = [ {name: 'Amsterdam1', id: '1'}, {name: 'Amsterdam2', id: '2'}, {name: 'Amsterdam3', id: '3'} ]; T ...

Select numerous files and conveniently delete them using the angular delete button

Background: In one of my tables, there is a column where users can either choose or upload files as input. I have implemented a feature that allows users to select multiple files at once. Issue at Hand: What I am trying to achieve is to have an 'x&ap ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...

Issue: Unable to locate 'child_process' in Angular 5

I am a newcomer to Angular, and I have encountered a requirement in my project to retrieve the MAC address of the user's system. To achieve this, I performed an NPM installation as shown below: npm install --save macaddress Next, I added the follow ...

How can I use a string from an array as a key in an object using TypeScript?

I have been utilizing a for loop to extract strings from an array, with the intention of using these strings as object keys. Although this code successfully runs, TypeScript raises a complaint: const arr = ['one', 'two']; const map = ...

Utilizing Ace with a personalized theme in Angular 2 application while straying away from the default theme directory

I am currently facing an issue with integrating an Ace editor into my Angular 2 application, which is built using angular-cli. I want to link the Ace editor to a custom theme stored in the app's assets folder src/app/assets instead of within node_modu ...