首页 > 解决方案 > Mat-Select 返回未定义

问题描述

我正在使用 Angular 材料并使用 Mat-Select。当用户进行选择时,我想抓取一个用户,该用户实际上是一个具有 Id 和 description 属性的对象。

<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> 

当用户做出选择时,我在这里收到未定义:

public selectUserType(userType: OxygenUserType) {
    console.log('selected');
    this.selectedUserType = userType;
    console.log(this.selectedUserType);
}

我也尝试过(selectionChange)="selectUserType($event.value)",但这不会产生对象。我需要用户选择是一个看起来像这样的对象:

{id:1, description:Agent},
{id:2, description:Dealer}

此对象基于此接口

export interface OxygenUserType {
    id: number;
    description: string;
}

标签: javascriptangularangular-material

解决方案


您可以使用[(value)]设置选定的用户。在选项的值中分配用户对象,而不仅仅是描述为:

<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);
}

推荐阅读