angularangular-materialangular2-templateangular2-directivesangular2-material

Angular2 get values of dynamically created inputs


I have this input which are created dynamically from list column, now I need to get all values of the inputs when some method occurs( imagine getAllValues() )

      <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>

Which would be the angular2 way of getting the values of all the generated inputs?


Solution

  • The easiest way to do it is by using 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>
    

    Then you will have the access to myForm.form.value object in getAllValues() function. Plnkr: https://plnkr.co/edit/84mzcNJliMmvszPq3xMm?p=preview