Angular 2 template driven form with ngFor inputs

夙愿已清 提交于 2019-12-29 05:50:30

问题


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?


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/39615780/angular-2-template-driven-form-with-ngfor-inputs

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