ngFor中的ngModelGroup?

时间:2017-04-25 16:33:25

标签: javascript angular angular-ngmodel angular2-ngmodel

如何检索嵌套在NgModelGroup内的NgFor的验证状态?

如果我没有NgFor,我可以将该组分配给这样的模板变量:

<p *ngIf="addressCtrl.invalid">Address is invalid.</p>

<div ngModelGroup="address" #addressCtrl="ngModelGroup">
    <input name="city"  [ngModel]="address.city"  required>
    <input name="state" [ngModel]="address.state" required>
    <input name="zip"   [ngModel]="address.zip"   required>
</div>

但我希望有这样的东西:

<p *ngIf="addressCtrl.invalid">Address # {{index}} is invalid.</p>

<div *ngFor="let address of addresses">
    <div ngModelGroup="address" #addressCtrl="ngModelGroup">
        <input name="city"  [ngModel]="address.city"  required>
        <input name="state" [ngModel]="address.state" required>
        <input name="zip"   [ngModel]="address.zip"   required>
    </div>
</div

问题是我得到addressCtrl未定义。

这是我用以下方法创建的一个用于测试的弹药:https://plnkr.co/edit/RXi2T52kynsWLr4fDMVa?p=preview

2 个答案:

答案 0 :(得分:2)

如果你移动它似乎工作正常

<p *ngIf="addressCtrl.invalid">Address # {{index}} is invalid.</p>

在迭代中。

你的plunker有一些不同的代码,所以它会是:

<p *ngIf="group.invalid">Address # {{index}} is invalid.</p>

你的分叉

Plunker

答案 1 :(得分:1)

addressHistory valid? {{ myHistoryGroup.valid }}
<ul ngModelGroup="addressHistory" #myHistoryGroup="ngModelGroup">
    <li *ngFor="let i = index; let address of addressHistory">
        <div [ngModelGroup]="i" #myLi="ngModelGroup">
        address valid? {{ myLi.valid }}
            <input type="text" [(ngModel)]="address.state" name="state" />
            <input type="text" [(ngModel)]="address.country" name="country" />
        </div>
    </li>
</ul>

<!--
#myForm.value will be like this:

{ "addressHistory": { "0": { ... }, "1": { ... }}, ... }
-->

是的,你可以这样使用它。