how to make mat-select in project dynamic to handle both single and multiple selection value for reuse

3k Views Asked by At

i want to make mat-selection component reuusble in whole project. so i am already using mat-select with single option selection and its working fine here is its code this is the config i send to component

 {
    type: "select",
    label: "Select Type of Model",
    name: "type",
    //    value: "UK",
    options: ['Physical Product', 'Post', 'Event Tickets', 'Subscription']
}

and here is my component html

<mat-form-field class="demo-full-width margin-top" [formGroup]="group">
<mat-select [placeholder]="field.label" [formControlName]="field.name">
<mat-option *ngFor="let item of field.options" [value]="item">{{item}}</mat-option>
</mat-select>

and here is component.ts

 import { FormGroup } from '@angular/forms';
 import { Component, OnInit } from '@angular/core';
 import { FieldConfig } from 'src/app/shared/models/forms';

 @Component({
 selector: 'app-select',
 templateUrl: './select.component.html',
 styleUrls: ['./select.component.scss']
 })
 export class SelectComponent implements OnInit {

 field: FieldConfig;
 group: FormGroup;
 constructor() {}
 ngOnInit() {}

 }

so i want it to handle multiple selection too i will just give it to this config

 {
type: "select",
label: "Select Type of Model",
name: "type",
//    value: "UK",
multiple:true,
showValueKey:'name',
returnValueKey:'id'
options: [{name:'Physical Product',id:1}, {name:'Physical Product',id:2}]
}
1

There are 1 best solutions below

0
On

If you take a look into the Properties section of MatSelect API https://material.angular.io/components/select/api#MatSelect you will find

@Input()
multiple: boolean

Which means you can pass a boolean value to this @Input() property which you already have in your object. E.g multiple: true. You can pass true / false to enable or disable the multi select.

<mat-select [multiple]="field.multiple">
    <!-- options -->
</mat-select>