angular material md-select select 默认第一个值

angular material md-select select default first value

当数据来自管道时,如何让默认的第一个选项被选中?

<md-select formControlName="key">
   <md-option *ngFor="let elem of (elements | TesxtFilter) ; let i = index"  [value]="elem .value">
        {{ elem.name }}
   </md-option>
</md-select>

使用索引:

<md-option *ngFor="let elem of (elements | TesxtFilter) ; let i = index"  [value]="elem .value" [selected]="i === 0">

你基本上是说如果 index0 (第一个选项) 它应该是 selected.

您可以 select 使用此选项:[selected]="condition"

更新 1:

我认为 select 的值决定了哪个选项实际上是 selected。无论如何,在我看来,你的 select 中应该始终包含 ngModel。试试这个代码,请让我知道:

在你的 html:

<md-select formControlName="key" [(ngModel)]="myDefaultOption">
   <md-option *ngFor="let elem of (elements | TesxtFilter) ; let i = index"  [value]="elem.value">
        {{ elem.name }}
   </md-option>
</md-select>

在你的组件中:

myDefaultOption = this.elements[0].value; // Here you should select the first option's value of the array of options for the select

如果您想查看文档:https://github.com/angular/material2/blob/master/src/lib/select/select.md#getting-and-setting-the-select-value

基本上,正常的 Angular 2 个过程 (我回答的第一部分) 不起作用。

你需要做什么(我正在解释上面的代码)是在你的组件中存储默认的并引用它在 md-select 中的 ngModel 中。然后 selected 值将是 md-option,它具有 valuemd-select.

中的 ngModel 中引用的值

更新 2:

如评论中所述,如果您需要 selected 选项 通过管道过滤的项目集合 的第一个选项,那么您应该申请组件中的 @Pipe,然后管理过滤后的集合。

import { TextFilter } from './text-filter.pipe';
class MyClass {

  filteredElements;
  constructor(private textFilter: TextFilter) {
      this.filteredElements = this.textFilter.transform(this.elements); // We apply the pipe to the 'elements' collection
      myDefaultOption = this.elements[0].value; // We select the first option of the filtered 'elements' collection
  }  
}

在你的 HTML:

<md-select formControlName="key" [(ngModel)]="myDefaultOption">
   <md-option *ngFor="let elem of filteredElements; let i = index"  [value]="elem.value">
        {{ elem.name }}
   </md-option>
</md-select>