2016-12-17 64 views
6

如何在ngModel中使用動態變量?Angular 2 - ngModel中的動態變量

我嘗試使用下面的代碼,但出現以下錯誤:

<div *ngFor="let num of ['1','2','3']; let i=index"> 
    <input id="qtd{{num}}" [(ngModel)]="qtd{{num}}" type="text"/> 
</div> 

埃羅

Unhandled Promise rejection: Template parse errors: Parser Error: Got interpolation ({{}})

+1

使用數組,並使用'qtd [num]'。 –

+0

你能舉個例子嗎? – rafaelcb21

回答

14

定義的組件陣列,並保持它推。

export class AppComponent { 
    qtd:any[] = {}; 
} 

然後,更新您的模板一樣

<div *ngFor="let num of ['1','2','3']; let i=index"> 
    <input id="qtd{{num}}" [(ngModel)]="qtd[num]" type="text"/> 
</div> 

{{ qtd | json}} 

在這所有的動態模型將在QTD陣列

Plunker

希望幫助!

+0

它工作得很好!謝謝!我一直在尋找正確的答案几個小時!謝謝! :) –

7

比方說,你有以下組件

export class AppComponent { 
    qtd1 = 'qtd1'; 
    qtd2 = 'qtd2'; 
    qtd3 = 'qtd3'; 
} 

,那麼你的模板可能看起來像:

<div *ngFor="let num of ['1','2','3']; let i=index"> 
    <input id="qtd{{num}}" [(ngModel)]="this['qtd' + num]" type="text"/> 
</div> 

Plunker Example