[英]Cannot set set Angular Material mat-select default option
我使用mat-select并在加载选项后尝试设置默认值。 我的问题是:
1.是否可以在填充 select 列表时设置项目? 这是 y select 列表的配置,我在其中设置选项:
this.listControls = [
{
id: 'employee',
type: 'select',
options: this.listEmployees().pipe(
map((list: PaginatedList) => {
return list.items.map(x => {
x.name = `${x.name} (${x.count})`;
return x;
});
})
)
},
];
2.是否可以在不使用ngModel
的情况下设置默认选项(选择其中一项)? 我只是有一个 object 值,但我不能让它被选中?
employee = {
id: 100,
name: 'Jonathan'
}
我也尝试对this.listControls[0]
应用过滤器,但由于它被填充为“可观察”,它不起作用:
const test = this.listControls[0].options.filter(x => x.id === 100);
尝试使用:
app.component.ts
import { HttpClient } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { map } from "rxjs/operators";
/** @title Select with 2-way value binding */
@Component({
selector: "select-value-binding-example",
templateUrl: "select-value-binding-example.html"
})
export class SelectValueBindingExample implements OnInit {
selected = "option2";
listControls: any = [];
constructor(private http: HttpClient) {}
async ngOnInit() {
this.listControls = [
{
id: "employee",
type: "select",
options: this.listEmployees().pipe(
map((list: any) => {
return list.data;
})
),
value: this.listEmployees().pipe(
map((list: any) => {
return list.data[0].first_name;
})
)
}
];
this.listControls.map((item: any, index: any) => {
this.listControls[index].value.subscribe((data: any) => {
this.listControls[index]["value"] = data;
});
});
}
listEmployees() {
return this.http.get("https://reqres.in/api/users?page=2");
}
}
app.component.html
<div *ngFor="let item of listControls">
<mat-form-field appearance="legacy">
<mat-label>Select an option</mat-label>
<mat-select [(value)]="item.value">
<mat-option>None</mat-option>
<mat-option
*ngFor="let item of item.options | async"
[value]="item.first_name"
>{{item.first_name}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
这里是stackblitz的工作示例: https://stackblitz.com/edit/angular-r4u37v-crowwk?file=src/app/select-value-binding-example.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.