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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With