【问题标题】:Cannot set set Angular Material mat-select default option无法设置设置角度材质垫选择默认选项
【发布时间】:2021-02-08 07:52:38
【问题描述】:

我使用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);

【问题讨论】:

  • 似乎listControls的内容是一些定制的类型。同样,PaginatedList 既不是 Angular 也不是 Material 默认类型。除非您向我们提供 stackblitz 示例,否则很难说为什么某些东西有效或无效。如果它是专有代码 - 你应该问作者。我想研究 MatSelect 的 compareWith 属性可能会让你走上正轨。
  • MatSelect 比较对象的引用,而不是它们的值。如果您对自己的对象进行硬编码并期望它被选中,仅仅因为它具有相同的值,那将是行不通的。您需要已经将该对象提供给 MatSelect 才能将其设置为选定对象。

标签: javascript angular rxjs angular-material observable


【解决方案1】:

尝试使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 2021-10-07
    • 2022-11-28
    • 2017-06-27
    • 2019-04-07
    • 1970-01-01
    相关资源
    最近更新 更多