如何获取当数据来自管道时选择的默认第一选项?角度材质md-select选择默认第一个值
<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-select选择默认第一个值
<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
是 (第一个选项)应该选。
您可以使用以下选项来选择一个选项:[selected]="condition"
。
更新1:
我认为选择的值是用于确定哪些选项实际上被选择的一个。无论如何,在我看来,你应该始终在select
中有ngModel
。如果你想看到的文档
myDefaultOption = this.elements[0].value; // Here you should select the first option's value of the array of options for the select
:试试这个代码,让我知道请:
在你的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>
基本上,正常的Angular 2程序(我的答案的第一部分)不起作用。
你需要做的(我解释上面的代码)是默认值存储在您的组件,并在您md-select
引用它在ngModel
。然后,选定的值将为md-option
,其value
为您的md-select
中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>
我发现了如何,检查我的更新。我将获取文档,以便我也可以链接它供您查看。祝你今天愉快! :D – SrAxi