gpt4 book ai didi

Angular mat-select value 2 way 使用对象进行数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 03:20:55 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于Angular mat-select value 2 way 使用对象进行数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54846985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com