1
votes

I can't work out how to send the selected value to a function in a mat-select. All the examples I have seen use ngModel.

In the ipad version of my app I have a mat-select where on the desktop version I have a list with a (click) on each item. On the desktop version if I click the item I can get the item's id because it is inside the *ngFor.

On a mat-select the (valueChange) is above and outside of the *ngFor. So how do I send the id of the selected option to the valueChange function?

<mat-select (valueChange)="consolelog(**Need to pass catalog.id here**)">
 <mat-option *ngFor="let catalog of catalogTitles" value="catalog.title">{{catalog.title}}</mat-option>
</mat-select>
4

4 Answers

3
votes

change value attribute to be catalog insted of catalog.title so you can get the full selected object on mat-select through change value event

Example:

HTML

<mat-select (valueChange)="changeValue($event)">
 <mat-option *ngFor="let catalog of catalogTitles" [value]="catalog">{{catalog.title}}</mat-option>
</mat-select>

TS

  catalogTitles = [
    {id:1,title:'aaa'},
    {id:2,title:'bbb'},
    {id:3,title:'ccc'},
    {id:4,title:'ddd'},
  ]

  changeValue(value:any){
    console.log(value.id)
  }

Another Solution : if you need to let value attribute with catalog.title or catalog.id you can get the value then filter the main array with these value to get the right object example HTML

<mat-select (valueChange)="changeValue($event)">
 <mat-option *ngFor="let catalog of catalogTitles" [value]="catalog.title">{{catalog.title}}</mat-option>
</mat-select>

TS

  catalogTitles = [
    {id:1,title:'aaa'},
    {id:2,title:'bbb'},
    {id:3,title:'ccc'},
    {id:4,title:'ddd'},
  ]

  changeValue(value:any){
    let selectedItem:any;
    selectedItem = this.catalogTitles.filter(item => item.title == value)[0]
    console.log(selectedItem.id)
  }
0
votes

You can simply add ngModel to the Select dropdowns.

<mat-select [(ngModel)]="cat" (valueChange)="print(cat)">

and in TS,

print(cat:any){
  console.log(cat.id);
}
0
votes

This sets up two way binding to a variable called catId in your ts class.

Then set option value to catalog.id instead of catalog.title.

html:

<mat-select [(value)]="catId">
 <mat-option *ngFor="let catalog of catalogTitles" value="catalog.id">{{catalog.title}}</mat-option>
</mat-select>

<p>
{{catId}}
</p>

ts:

export class MyClass {

catId: number;
//etc
0
votes

Hope this helps...

app.component.html

<mat-form-field>
<mat-select [(ngModel)]="selectedCatlog" (valueChange)="onSelection()">
  <mat-option *ngFor="let catlog of catalogTitles" [value]="catlog.title">{{catlog.title}}
  </mat-option>
</mat-select>

app.component.ts

onSelection() {
console.log(this.selectedCatlog);    
}