2016-07-17 89 views
4

我想一個字符串數組從我的輸入綁定,所以在HTML文件中我寫了這一點:Angular2 ngModel內的ngFor

<div *ngFor="let word of words; let in=index" class="col-sm-3"> 
     <div class="form-group"> 
     <input type="text" [(ngModel)]="words[in]" class="form-control" [attr.placeholder]="items[in]" required> 
     </div> 
    </div> 

但因爲當我登錄的預期並沒有工作words變量它顯示一個空數組,在我的Component類中初始化。另外,我應該從另一個組件記錄變量,應該是我的問題。我有兩個組件:

  • 包含查詢組件數組的表單組件。
  • 具有單詞字符串數組的查詢子組件。

因此,詞語變量聲明到查詢部件,但我記錄通過窗體部件這樣這個變量:

console.log(JSON.stringify(this.queries)); 

雖然查詢是查詢的形式分量的數組:

queries:Query[] = []; 

感謝您的幫助!

+0

對我來說,問題不明確。如果你能明確告訴你究竟想要什麼? – micronyks

+0

經過多次測試後,我的問題是在更新後將查詢字發送回我的表單組件 –

+0

每個輸入標籤必須具有定義的唯一名稱屬性。 http://stackoverflow.com/questions/39336708/angular2-ngmodel-inside-ngfor-data-not-binding-on-input –

回答

12

問題是在ngFor中使用原始值數組(words)。

你可以改變的話對象的數組像

words = [{value: 'word1'}, {value: 'word2'}, {value: 'word3'}]; 

,並使用它像

<div *ngFor="let word of words; let in=index" class="col-sm-3"> 
     <div class="form-group"> 
     <input type="text" [(ngModel)]="words[in].value" class="form-control" [attr.placeholder]="items[in]" required> 
     </div> 
    </div> 

這也可能使用trackBy是可以解決的,但我不知道。

+0

你好,那裏!你能解釋一下這個問題嗎?老實說,我沒有得到什麼OP是問,但兩種方式(基元或對象的數組)似乎工作正常:http://plnkr.co/edit/7ePXDWCwfeI0WglCj3KN?p=preview ... – acdcjunior

+0

我試過這個但仍然不起作用。順便說一句,我試圖在我的輸入上添加事件關鍵字並將單詞數組記錄在同一個組件中。記住它的工作,所以我的問題是溝通單詞數組到表單(父)組件。 –

+1

@ e.m.b「不起作用」不提供太多信息。 –

1

通過使用@Input()函數並傳遞查詢數組+查詢索引號來解決此問題。謝謝你們的支持。

3

每個輸入標籤必須具有唯一的 'name' 屬性定義的,如描述在:

Angular2 ngModel inside ngFor (Data not binding on input)

這裏是校正後的代碼:

<div *ngFor="let word of words; let in=index" class="col-sm-3"> 
    <div class="form-group"> 
    <input type="text" [(ngModel)]="words[in]" name="word{{in}}" class="form-control" [attr.placeholder]="items[in]" required> 
    </div> 

+0

是的,我遭受了這個,並通過提供不同的名稱解決。 非常感謝 –