当数据来自管道时,如何选择默认的第一个选项?
<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">
您基本上说的是,如果index
是 0 (第一个选项(应该选择。
您可以使用以下方式选择一个选项: [selected]="condition"
。
更新1:
我认为选择的值是确定实际选择哪个选项的值。无论如何,我认为,您应该始终在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/src/lib/select/select/select.md#getting-andting-andting-and-setting-the-select-value/P>
基本上,正常的角度2步骤(我答案的第一部分(不起作用。
您需要做的(我正在解释上面的代码(是在组件中存储默认的 value ,并将其引用在md-select
中的ngModel
中。然后,选定的值将是md-option
,它是value
的CC_8,在您的ngModel
中引用的值。
更新2:
如在评论中所述,如果您需要作为选定的选项通过物品的管道收集过滤的第一个选项,则应在组件中应用@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>