Angular mat-select value 2 way Data binding using object

时间:2019-02-23 22:41:03

标签: angular select angular-material

In an Angular html template I have an select element with mat-select directive (Angular Material) which loads data from an object stored in a property called "selectedCriteria" in a service .ts file. Three types of object can be stored in the "selectedCriteria" property based on application logic and all of them have "name" variable of type String. So I want to load the object name in this select element. Problem is when the app loads, the select element does not load/show the "selectedCriteria" because it's an object and not a string. I can use selectedCriteria.name to bind it with a string value, but that will add additional code to convert from object to string and vice versa for two way data binding. What is the solution to load an object in this select element during app startup?

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

1 个答案:

答案 0 :(得分:0)

您可以按照以下步骤进行操作。

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 Example