Search code examples
angular-material-5

how to pass data to angular material select to use more the one select in one form


I am trying to use the angular material select as component in my application to use that component multiple place in one form ideally.

but my question is how to pass the data to each of this select component to load with different data.

is that any way as like mat-table do we use datasource for that ?

or any other way please enlighten me.

refer my stackbliz code;

https://stackblitz.com/edit/angular-hfdyev?file=app%2Fselect-value-binding-example.html


Solution

  • You can create your own 'wrapper' component around the form field and select components and give it a 'datasource' input that the component understands. For example:

    select-field-component.ts

    import {Component, Input} from '@angular/core';
    
    @Component({
        selector: 'select-field',
        templateUrl: 'select-field-component.html'
    })
    export class SelectFieldComponent {
        @Input() datasource: any[];
        @Input() label: string;
        @Input() labelKey: string;
        @Input() value: any;
        @Input() valueKey: string;
    }
    

    select-field-component.html

    <mat-form-field>
        <mat-label *ngIf="label">{{label}}</mat-label>
        <mat-select [(value)]="value">
            <mat-option *ngFor="let item of datasource" [value]="item[valueKey]">
                {{item[labelKey]}}
            </mat-option>
        </mat-select>
    </mat-form-field>
    

    Obviously, this is a simple example - you could add a lot more features. Here it is in action on StackBlitz.