首页 > 解决方案 > Angular mat-select value 2 way 使用对象的数据绑定

问题描述

在 Angular html 模板中,我有一个带有 mat-select 指令(Angular Material)的选择元素,它从存储在服务 .ts 文件中名为“selectedCriteria”的属性中的对象加载数据。根据应用程序逻辑,“selectedCriteria”属性中可以存储三种类型的对象,它们都具有String类型的“name”变量。所以我想在这个选择元素中加载对象名称。问题是当应用程序加载时,选择元素不会加载/显示“selectedCriteria”,因为它是一个对象而不是字符串。我可以使用 selectedCriteria.name 将其与字符串值绑定,但这将添加额外的代码以从对象转换为字符串,反之亦然,用于双向数据绑定。在应用程序启动期间在此选择元素中加载对象的解决方案是什么?

<mat-form-field style="width: 45%; display: inline-block">
      <mat-select placeholder="Criteria" [(value)]="reportService.selectedCriteria" (valueChange)="reportService.filterSalesData()">
        <mat-option *ngFor="let criteria of reportService.criteriaList" [value]="criteria">{{criteria.name}}</mat-option>
      </mat-select>
      </mat-form-field>

标签: angularselectangular-material

解决方案


您可以按如下方式执行此操作。

HTML

 <mat-form-field style="width: 45%; display: inline-block; margin-right: 40px;">
  <mat-select [(ngModel)]="selectedCriteria" (selectionChange)="onSelectValueChange()">
    <mat-option *ngFor="let criteria of criteriaList" [value]="criteria">{{criteria.name}}</mat-option>
  </mat-select>
</mat-form-field>

TS

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
selectedCriteria: User;
criteriaList: User[] = [
  { name: 'John Doe'},
  { name: 'Albert Einstein'},
  { name: 'Isaac Newton'}
];


ngOnInit(){
  this.selectedCriteria = this.criteriaList[0];
}

onSelectValueChange () {
  console.log(this.selectedCriteria);
  console.log('Type of Selection => ', typeof this.selectedCriteria);
}
}

interface User{
  name: string;
}

StackBlitz 示例


推荐阅读