4

我有這個輸入,從列表column動態創建的,現在我需要的時候一些方法,也可以看到的所有輸入的值(想象getAllValues()Angular2得到的動態創建的輸入值

 <div *ngFor="let cell of column; let i = index;"> 
       <!-- Material design input--> 
       <md-input type="{{cell.type}}" 
       value="{{getInputValue(cell)}}" 
       [placeholder]="cell.label"> 
       </md-input> 
     </div> 

這將是獲取所有生成輸入的值的方法?

+0

可以使用ViewChildren,如果這是他們可以通過編程附加到表單的表單的一部分(反應)或魔法(模板驅動)。 – silentsod

+0

@silentsod最佳做法是什麼?反應或魔法? – commonSenseCode

+0

模板驅動或多或少符合Angular 1的處事方式,Reactive是更重的代碼明智的,但使單元測試更容易。兩者都不是最佳實踐,模板驅動可能是一種在學習和實際代碼方面較低的開銷方法。 如果它不在表單中,那麼你可能會想要做一個ViewChildren查詢來獲取它們。 – silentsod

回答

5

做到這一點,最簡單的方法是使用ngForm

<form #myForm="ngForm"> 
     <div *ngFor="let cell of column; let i = index;"> 
      <md-input [type]="cell.type" 
      [name]="cell.name"  <!-- Note the 'name' has to be set --> 
      [ngModel]="cell.value" 
      [placeholder]="cell.label"></md-input> 
     </div> 
     <a (click)="getAllValues(myForm)">print values</a> 
</form> 

然後,你將有getAllValues的訪問myForm.form.value對象()函數。 Plnkr:https://plnkr.co/edit/84mzcNJliMmvszPq3xMm?p=preview

0

我所做的是:

在組件類
   <md-input #input // NOTICE #input 
          type="{{cell.type}}" 
          value="{{getInputValue(cell) || '--'}}" 
          [placeholder]="cell.label"></md-input> 

export class MyComponent { 

    @ViewChildren('input') inputs; 


    public updateData(): void { 
     console.log(this.inputs) //this will give access to id and values (explore it on google chromes console) 
     console.log(this.inputs.toArray().map(x => x.value)) // this gives access to values 
    } 
} 
+0

如果使用** ngFor **語句動態生成輸入,則無法以此方式使用模板變量 – Sal