Home > Software engineering >  How can i pass field names dynamicly to the a component
How can i pass field names dynamicly to the a component

Time:04-21

I am trying to build a reusable component based on the mat-select / mat-option component from Angular Material.

My template looks like this

<mat-select
    #select  
    placeholder="Tract List"
    formControlName ="multiselect"
    multiple>
    <div >
        <mat-checkbox 
            (change)="toggleAllSelection()">{{selectAllText}}</mat-checkbox>
    </div>
    <mat-option (click)="optionClick()" *ngFor="let List of  data" [value]="List.guid">{{ List.name}}</mat-option>
</mat-select> 

What I am looking for is a way to pass in the actual [value] field and whats displayed which is currently {{List.name}} I ideally want to be able to specify the name of the field to use or even be able to specify a string like List.text2 " - " List.id

How can I achieve this ?

CodePudding user response:

There are several ways to achieve this, but the easiest to explain and understand is with a simple 'property binding' between componets: https://angular.io/guide/property-binding

You can do a component with your code (for instance, with the name 'app-mymultiselect'), and add to it two Input attributes (data and fieldNameToShow) :

import { Component } from "@angular/core";
...
@Component({
    selector: 'app-mymultiselect',
    templateUrl: './mymultiselect.component.html',
    styleUrls: ['./mymultiselect.component.scss']
})
export class MymultiselectComponent{

@Input() data!: any[]; // Type it depending on your data list elements
@Input() fieldNameToShow: string = 'name'; // name or id or whatever you like by default
...

And in its HTML, something like this:

<mat-option (click)="optionClick()" *ngFor="let List of data" [value]="List.guid">{{ List[fieldNameToShow] }}</mat-option>
</mat-select>

Then, for use it in any of your components, you only have to add in the HTML something like this:

<app-mymultiselect [data]="youArrayOfElements" [fieldNameToShow]="fieldNameToShow"></app-mymultiselect>

Being its value in the ts file:

  • 'youArrayOfElements' a variable/attribute with the list of object you want the select to show.
  • 'fieldNameToShow' a variable/attribute string, with the object's name you want to show (for instance, fieldNameToShow = 'id');
  • Related