2017-05-08 128 views
2

如何获取当数据来自管道时选择的默认第一选项?角度材质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> 
+0

我发现了如何,检查我的更新。我将获取文档,以便我也可以链接它供您查看。祝你今天愉快! :D – SrAxi

回答

1

使用索引:

<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> 

在你的组件https://github.com/angular/material2/blob/master/src/lib/select/select.md#getting-and-setting-the-select-value

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

你需要做的(我解释上面的代码)是默认存储在您的组件,并在您md-select引用它在ngModel。然后,选定的值将为md-option,其value为您的md-selectngModel中引用的值。

更新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> 
+0

它不起作用。我有一个错误“无法绑定到'选中',因为它不是'md-option'的已知属性”“ [attr.selected] - >不会导致错误,但它不起作用 – Vero

+0

@维罗我明白了。试试我更新的代码。让我们来看看它。我正在深入研究'md-select'。 – SrAxi

+0

元素是一个原点数组(在过滤之前)。 如果管道过滤器拒绝元素的第一个元素,该怎么办? 元素[0]不会在的选项中,元素[1]可能是第一个 – Vero