Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Select Optional Multiple Selects

Hello I'm trying to wrap the angular material select in a shared component. Everything is working like a charm except for only one thing, And that is the "multiple" property.

I'm trying to bind to a "@Input()" property "multiple", the code is as follows

dropdown.component.ts

import { Component, Input } from '@angular/core';

@Component({
    selector: 'dropdown',
    templateUrl: './dropdown.component.html',
    styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent {
    @Input() dropdownLabel: string;
    @Input() categorized: boolean = false;
    @Input() multiple: boolean = false;
    @Input() data: any[] = [];
}

dropdown.component.html

<mat-form-field>
    <mat-label>{{ dropdownLabel }}</mat-label>
    <mat-select multiple="multiple">
        <!-- If is categorized add groups -->
        <ng-container *ngIf="categorized">
            <mat-optgroup *ngFor="let group of data" [label]="group.name">
                <mat-option *ngFor="let item of group.children" [value]="item">{{ item.name }}</mat-option>
            </mat-optgroup>
        </ng-container>

        <!-- if is not categorized add elements without groups -->
        <ng-container *ngIf="!categorized">
            <mat-option *ngFor="let item of data" [value]="item">{{ item.name }}</mat-option>
        </ng-container>
    </mat-select>
</mat-form-field>

I've tried in the html file when I type multiple="false" or "true", it works.

But when I bind it to the variable "multiple" in my js file that has a default value "false", it always activates the multiple selection behavior.

Any idea how to get around this?

Thanks in advance!

like image 833
Willy Avatar asked Jul 18 '26 03:07

Willy


1 Answers

When you bind with the following syntax:

multiple="multiple"

the multiple property is bound to the string "multiple". Since any non empty string is truthy, the multiple property is activated. Apparently, Angular Material interprets the string "false" as falsy; so that the following syntax turns off the multiple option of the select component:

multiple="false"

To make sure that Angular evaluates the expression multiple correctly, use the property binding syntax with the brackets:

[multiple]="multiple"

See this stackblitz for a demo.

like image 183
ConnorsFan Avatar answered Jul 20 '26 22:07

ConnorsFan