2016-11-24 129 views
0

我有一個ngFor循環,看起來像這樣(簡化,以便更容易跟蹤):綁定選擇下拉選項變量

<div *ngFor="let c of customers"> 
    <button class="save green-button" type="button" (click)="editCustomer(c.CustomerId, method.value)">Save</button> 

    <select *ngIf="c.GrowMethodsAvailable.length" id="PerProjectGrowMethodId" name="PerProjectGrowMethodId" #method> 
     <option *ngFor="let method of c.GrowMethodsAvailable" [ngValue]="method.Value">{{method.Text}}</option> 
    </select> 
</div> 

正如你所看到的,存在保存按鈕和一個選擇下拉與動態選項。當我點擊保存按鈕時,我需要它發送我從相應下拉列表中選擇的任何值。我知道如何將值綁定到我在我的類中創建的變量,但可能會有10個不同的保存按鈕,並選擇了10個不同的值,所以我認爲每個選擇下拉列表都需要一個局部變量。我將#method添加到select元素,並在保存按鈕中將method.value添加到我的(click)="editCustomer(c.CustomerId, method.value)"函數中。當我嘗試這一點,我得到了以下錯誤:

Cannot read property 'value' of undefined

我怎樣才能從我所選選項的值綁定到對應的保存按鈕,以便我發送正確的價值觀爲每一個?

回答

0

與綁定有關的問題是內部重複#method爲客戶打破了select中的模板引擎的句柄。要改變它,並使其工作,我們需要改變我們的方法和溝渠模板變量,因爲它們是靜態定義的:

我們可以在這裏濫用JS爲了我們的緣故,在您的組件中添加一個屬性來跟蹤所選項目:

component.ts

selected = []; 

在HTML模板中,我們會訪問該按鈕屬性和選擇:

<div *ngFor="let c of customers"> 
     <button class="save green-button" type="button" (click)="editCustomer(c.CustomerId, selected[c.CustomerId])">Save</button> 

     <select *ngIf="c.GrowMethodsAvailable.length" [(ngModel)]="selected[c.CustomerId]"> 
      <option *ngFor="let method of c.GrowMethodsAvailable" [ngValue]="method.Value">{{method.Text}}</option> 
     </select> 
    </div> 

Plunker:http://plnkr.co/edit/bWnlJfydPbUxeeI6a715?p=preview

+0

我在記錄i.value到控制檯時,我點擊保存在我的應用程序和你的plnkr,它回來的時候是未定義的。 – Brett

+0

進一步閱讀(我的道歉)表示模板變量綁定必須是靜態的。 https://github.com/angular/angular/issues/4581#issuecomment-148786554 – silentsod