本文介绍了带有ngFor输入的Angular 2模板驱动窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在模板驱动的表单中使用ngFor创建输入字段,并使用类似#name =ngModel的字样来在另一个标记中使用name.valid?



现在我们有一个包含数量字段的产品动态列表和一个表格中的添加到购物车按钮。我想把整个事情做成一个表单,在末尾添加全部按钮,如下所示:

 < form#form = ngForm > 
< div * ngFor =item in items>
< input name =product - {{item.id}}
[(ngModel)] =item.qty
#???? =ngModel
validateQuantity>
[disabled] =!????。valid>添加到购物车< / button>
< / div>
[disabled] =!form.valid>全部添加< / button>
< / form>

但是我怎么能为ngModel的每行生成一个新的变量名?

解决方案

没有必要这样做,就像这样做:

 < form#form =ngForm> 
< div * ngFor =item in items>
< input name =product - {{item.id}}
[(ngModel)] =item.qty
validateQuantity
#qtyInput>
[disabled] =!qtyInput.valid>添加到购物车< / button>
< / div>
[disabled] =!form.valid>全部添加< / button>
< / form>

它的Angular部分在这里。 :)

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?

解决方案

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

这篇关于带有ngFor输入的Angular 2模板驱动窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:55