Angular 2 template driven form with ngFor inputs

Jeppz picture Jeppz · Sep 21, 2016 · Viewed 22.6k times · Source

Is it possible to create input fields with a ngFor in a template driven form and use something like #name="ngModel" to be able to use name.valid in another tag?

Right now we have a dynamic list of products with a quantity field and a add to cart button in a table. I want to make the whole thing a form with a add all button at the end like this:

<form #form="ngForm">
    <div *ngFor="item in items">
        <input name="product-{{item.id}}"
               [(ngModel)]="item.qty"
               #????="ngModel"
               validateQuantity>
        <button (click)="addItemToCart(item)"
                [disabled]="!????.valid">Add to cart</button>
    </div>
    <button (click)="addAll()"
            [disabled]="!form.valid">Add all</button>
</form>

But how can i generate a new variable name per row for the ngModel?

Answer

slaesh picture slaesh · Sep 21, 2016

There's no need for this, just do it like this:

<form #form="ngForm">
    <div *ngFor="item in items">
        <input name="product-{{item.id}}"
               [(ngModel)]="item.qty"
               validateQuantity
               #qtyInput>
        <button (click)="addItemToCart(item)"
                [disabled]="!qtyInput.valid">Add to cart</button>
    </div>
    <button (click)="addAll()"
            [disabled]="!form.valid">Add all</button>
</form>

Its Angular's part here. :)