Issue
Is it possible to have 2 values for 1 mat-option
.
How can i achieve this kind of code with angular material?
<mat-select formControlName="type">
<mat-option [fruit,place]="mango,india">
fruit:mango, place: india
</mat-option>
</mat-select>
Solution
You can have an object or an array of string to achieve this:
in case of array of string, the data structure would be:
foods: Food[] = [
{viewValue: ['mango','india'], value: 'Ind'},
{viewValue: ['apple','america'], value: 'US'},
{viewValue: ['banana','colombia'], value: 'Col'}
];
in case of object, the data structure would be:
foodObj= [
{viewFruit: 'mango', viewCountry: 'india', value: 'Ind'},
{viewFruit: 'apple', viewCountry: 'america', value: 'US'},
{viewFruit: 'banana',viewCountry: 'colombia', value: 'Col'}
];
relevant HTML:
<h4>Basic mat-select (as string array)</h4>
<mat-form-field>
<mat-label>Favorite food (as string array)</mat-label>
<mat-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
fruit:{{food.viewValue[0]}}, place: {{food.viewValue[1]}}
</mat-option>
</mat-select>
</mat-form-field>
<h4>Basic mat-select (as object)</h4>
<mat-form-field>
<mat-label>Favorite food (as object)</mat-label>
<mat-select>
<mat-option *ngFor="let food of foodObj" [value]="food.value">
fruit:{{food.viewFruit}}, place: {{food.viewCountry}}
</mat-option>
</mat-select>
</mat-form-field>
relevant TS:
import {Component} from '@angular/core';
export interface Food {
value: string;
viewValue: string[];
}
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
foods: Food[] = [
{viewValue: ['mango','india'], value: 'Ind'},
{viewValue: ['apple','america'], value: 'US'},
{viewValue: ['banana','colombia'], value: 'Col'}
];
foodObj= [
{viewFruit: 'mango', viewCountry: 'india', value: 'Ind'},
{viewFruit: 'apple', viewCountry: 'america', value: 'US'},
{viewFruit: 'banana',viewCountry: 'colombia', value: 'Col'}
];
}
complete working stackblitz here
Answered By – Akber Iqbal
Answer Checked By – Pedro (BugsFixing Volunteer)