Javascript Mat Select返回未定义的
我正在使用角材质和Mat Select。当用户做出选择时,我想抓取一个用户,它实际上是一个具有Id和description属性的对象Javascript Mat Select返回未定义的,javascript,angular,angular-material,Javascript,Angular,Angular Material,我正在使用角材质和Mat Select。当用户做出选择时,我想抓取一个用户,它实际上是一个具有Id和description属性的对象 <mat-form-field> <mat-select placeholder="Select User Type" (selectionChange)="selectUserType(user)"> <mat-option *ngFor="let user of userTypeList" [value
<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>
我还尝试了(selectionChange)=“selectUserType($event.value)”
,但这不会生成对象。我需要用户选择的对象如下所示:
{id:1, description:Agent},
{id:2, description:Dealer}
此对象基于此接口
export interface OxygenUserType {
id: number;
description: string;
}
您可以使用[(值)]
设置所选用户。在选项的值中,将用户对象指定为,而不仅仅是说明:
<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);
}
{{user.description}}
公共onUserTypeChange(){
console.log(this.selectedUserType);
}
我认为你的方法行不通,因为你在mat选项中声明了你的用户,所以mat select不知道这一点
我会使用一个模型来解决这个问题,这样你就不需要一个函数来存储你的值。如果您想在模型更改时仍执行其他操作,可以在更改函数中调用模型中的值
因此,您的html将是:
<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>
当前您正在将
user.description
绑定到mat option
,因此当您选择一个选项时,selectionChange
的$event.value
将是user.description
。如果需要整个对象,只需将对象本身绑定到mat选项
.Thx即可。我试过了,效果很好。我遇到了另一个问题。一旦我从下拉列表中保存所选用户,视图更改后,选择将不再持续。这是因为您没有为mat select
提供初始值。为此,您应该通过[(ngModel)]
.Thx将其绑定为init值。我能够通过添加[(ngModel)]来解决问题。这对我来说很有效。。。我想补充一点,当谈到这个确切的特性时,angular文档并没有明确说明这一点。
<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>
public selectUserType() {
console.log('selected');
console.log(this.selectedUserType);
// do some stuff with your value.
}