Reputation: 611
I'm working with Angular material and using Mat-Select. When the user makes a selection I want to grab a user which is actually an object with a Id and description property.
<mat-form-field>
<mat-select placeholder="Select User Type" (selectionChange)="selectUserType(user)">
<mat-option *ngFor="let user of userTypeList" [value]="user.description">
{{ user.description }}
</mat-option>
</mat-select>
</mat-form-field>
When the user makes a selection I am receiving undefined here:
public selectUserType(userType: OxygenUserType) {
console.log('selected');
this.selectedUserType = userType;
console.log(this.selectedUserType);
}
I've also tried (selectionChange)="selectUserType($event.value)"
but this doesn't produce an object. I need the user selection to be an object that looks like this:
{id:1, description:Agent},
{id:2, description:Dealer}
This object is based on this interface
export interface OxygenUserType {
id: number;
description: string;
}
Upvotes: 2
Views: 7480
Reputation: 3743
I think your way doesn't work because you declare your user in mat-option, so mat-select doesn't know about this.
I would solve this by using a model so you don't need a function to store your value. If you want to still do some other stuff when the model changes you can call your value from the model in your change function.
so your html would be:
<mat-form-field>
<mat-select placeholder="Select User Type" [(ngModel)]="selectedUserType" (change)="selectUserType()">
<mat-option *ngFor="let user of userTypeList" [value]="user">
{{ user.description }}
</mat-option>
</mat-select>
</mat-form-field>
and in your method:
public selectUserType() {
console.log('selected');
console.log(this.selectedUserType);
// do some stuff with your value.
}
Upvotes: -1
Reputation: 5462
You can use [(value)]
to set selected user. In option's value assign user object rather than only description as:
<mat-select placeholder="Select User Type" [(value)]="selectedUserType" (selectionChange)="onUserTypeChange()">
<mat-option *ngFor="let user of userTypeList" [value]="user">
{{ user.description }}
</mat-option>
</mat-select>
public onUserTypeChange() {
console.log(this.selectedUserType);
}
Upvotes: 6