Angular2 get dynamically generated input values

I have this input, which is dynamically created from a list column, now I need to get all the input values ​​when any 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>

What will be the angular2 way to get the values ​​of all the generated inputs?

+4
source share
2 answers

The easiest way to do this is to use 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>

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

+5

:

              <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

Source: https://habr.com/ru/post/1660426/


All Articles