HachimJ
HachimJ

Reputation: 131

How do I get the values from the inputs that *ngFor generate in my .component.ts file?

As said in the title, I want to get the values from my generated inputs. How can I do that so I can work on them in my .ts file?

Here is the code so far for my blabla.component.html:

    <form #f="ngForm" (ngSubmit)="onSubmit(f)" class="form-horizontal">
    <input name="codeB" ngModel #codeB="ngModel" id="codeB" type="text" class="form-control frm" placeholder="Code Barre" />
    <input name="name" ngModel #name="ngModel" id="name" type="text" class="form-control frm" placeholder="Name Produit" />

    <table class="table table-striped">
            <tr *ngFor="let mag of listMagasins | async">
                <td>
                    <h4>{{mag.name}}</h4>
                </td>
                <td>
                    <input name="prix" ngModel #prix="ngModel" id="prix" type="text" 
                    class="form-control frm" placeholder="Price product" required />
                </td>
            </tr>
    </table>

    <!--<input name="nameMag" ngModel #nameMag="ngModel" id="nameMag" type="text"
     class="form-control frm" placeholder="Magasin" />-->

    <button class="btn btn-primary" type="submit">Ajouter</button>
</form>

Thank you for the help!

Upvotes: 1

Views: 1078

Answers (1)

silentsod
silentsod

Reputation: 8335

This can be achieved by naming things uniquely instead of naming each input prix and, if we want the values in the TS, using ViewChildren:

component.html

<tr *ngFor="let mag of listMagasins | async; let i = index;">
            <td>
                <h4>{{mag.name}}</h4>
            </td>
            <td>
                <input name="prix{{i}}" ngModel #prix="ngModel" id="prix" type="text" 
                class="form-control frm" placeholder="Price product" required />
            </td>
        </tr>

component.ts

import {ViewChildren} from "@angular/core"

export class ComponentClass {
     @ViewChildren('prix') inputs;
<...>
}

Which will set our form up to have separately bound controls and give us the inputs in the TS file.

Here's a Plunker you can mess with

Upvotes: 2

Related Questions