无法设置 set Angular Material mat-select 默认选项

时间:2021-02-08 07:52:38

标签: javascript angular rxjs angular-material observable

我使用 mat-select 并尝试在加载选项后设置默认值。我的问题是:

1. 是否可以在填充选择列表时设置项目?这是我在其中设置选项的 y 选择列表的配置:

  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 的情况下设置默认选项(选择其中一项)?我只有一个对象值,但我不能让它被选中?

employee = {
    id: 100,
    name: 'Jonathan'
}

我也尝试将过滤器应用于 this.listControls[0],但由于它被填充为“可观察”,因此不起作用:

const test = this.listControls[0].options.filter(x => x.id === 100);

1 个答案:

答案 0 :(得分:0)

尝试使用:

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