如何将数据传递到角度材料选择以在一个形式中使用多个选择



我正在尝试在我的应用程序中使用角度材料选择作为组件,以理想地在一个形式中多次使用该组件。

但我的问题是如何将数据传递给每个选择组件以加载不同的数据。

这是否像 mat-table 一样使用数据源

?或任何其他方式请启发我。

参考我的堆栈代码;

https://stackblitz.com/edit/angular-hfdyev?file=app%2Fselect-value-binding-example.html

您可以在表单字段周围创建自己的"包装器"组件并选择组件,并为其提供组件理解的"数据源"输入。例如:

select-field-component.ts

import {Component, Input} from '@angular/core';
@Component({
selector: 'select-field',
templateUrl: 'select-field-component.html'
})
export class SelectFieldComponent {
@Input() datasource: any[];
@Input() label: string;
@Input() labelKey: string;
@Input() value: any;
@Input() valueKey: string;
}

选择字段组件.html

<mat-form-field>
<mat-label *ngIf="label">{{label}}</mat-label>
<mat-select [(value)]="value">
<mat-option *ngFor="let item of datasource" [value]="item[valueKey]">
{{item[labelKey]}}
</mat-option>
</mat-select>
</mat-form-field>

显然,这是一个简单的例子 - 您可以添加更多功能。这是它在StackBlitz上的行动。

最新更新