Angular Material select dropdown API only emits a value. Both [(ngModel)]
and (selectionChange)
only emit single member , not the whole object data field.
For example eg, it only emits the food.value = 2, does not emit other class fields for a row list item, like foodName, foodDescription, foodWeight, etc, (need to emit all the corresponding members for a listId)
How do I emit the whole object for food, given an food.value ? Needs to work for Any Material Dropdown in the future created, not just specific cases. Does Material Angular have any specific options to allow this?
The answers below, only work for one particular example, trying to see larger picture.
https://material.angular.io/components/select/api
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select>
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
Class example, for 2, need foodCategory, Calories, and other fields, etc
export class SelectOverviewExample {
foods: Food[] = [
{value: '0', viewValue: 'Steak', foodCategory: 'Meat', Calories: 50},
{value: '1', viewValue: 'Pizza', foodCategory: 'Carbs', Calories: 100},
{value: '2', viewValue: 'Apple', foodCategory: 'Fruit', Calories: 25}
];
}
Does anyone have a better solution?
Otherwise, will to write this in the selectionChange
onOutput method. Seems like Angular Materials would have better option,
this.foods.find(x=>x.value =="2")
Note for solutions below; Need to have solution for any different classes, with many type of members, etc
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
formGroup: FormGroup;
titleAlert: string = 'This field is required';
selected;
data = [
{value: '0', viewValue: 'Steak', foodCategory: 'Meat', Calories: 50},
{value: '1', viewValue: 'Pizza', foodCategory: 'Carbs', Calories: 100},
{value: '2', viewValue: 'Apple', foodCategory: 'Fruit', Calories: 25}
];;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.selected = 0
}
}
<h4>Basic mat-select</h4>
<mat-form-field>
<mat-label>Favorite food</mat-label>
<mat-select [(value)]="selected">
<mat-option *ngFor="let food of data; let i = index" [value]="i">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<div>
Selected value: {{data[selected].foodCategory}}
</div>