Angular 2 template driven form with ngFor inputs

时光怂恿深爱的人放手 提交于 2019-11-29 03:29:00

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. :)

The mxii answer works as expected for form items dynamically created by ngFor, but if you're not going to use ngForm, and you're iterating over a list of items that have an independent entity (like a list of comments, and the user should be able to reply each comment) you can use template reference variables which give you the ability to get and work with the Input element easily.

Here is how you can do it:

// Your template
<div *ngFor="item in items">
  <!-- Your input -->
  <input #itemInput type="number">

  <button (click)="addItemToCart(itemInput.value)"
          [disabled]="!itemInput.value">Add to cart</button>
</div>

It gives a reference to the variable assigned to the input field, and here in the example above we passed itemInput.value which will be the value of the input field; There might be cases that you need a reference to the input field (let's say you're going to remove its value when you got the data), you can just pass the itemInput and which is a type of HTMLInputElement and access its data.

you need to add FormModule to your app.module.ts to get 2-way-binding working, at least in newer versions of angular

Angular 4 - "Can't bind to 'ngModel' since it isn't a known property of 'input' " error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!