2017-05-08 65 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