我有一个带有模板驱动验证的FormGroup。我需要我的公式来获得由ngFor创建的动态生成输入的一部分。不幸的是,angular2现在要求使用ngModel命名FormGroup中的每个输入。我怎么处理它?模板驱动的解决方案是优先的。表格代码如下:
<form #f="ngForm" (ngSubmit)="createProfile()">
<div class="row align-items-center mb-2">
<div class="col-sm-2">
<b>Name:</b>
</div>
<div class="col-sm-10">
<input type="text" [(ngModel)]="profile.name" class="form-control"
name="profileName" required pattern="[a-zA-Z_][a-zA-Z_\-0-9]*">
</div>
</div>
<div class="channelBox">
<div *ngFor="let c of profile.channels">
<div class="row align-items-center mb-2">
<div class="col-sm-2">
<b>Name:</b>
</div>
<div class="col-sm-10">
<input type="text" [(ngModel)]="c.name" class="form-control" required
pattern="[a-zA-Z_][a-zA-Z_\-0-9]*" name="channelName">
</div>
</div>
<div class="row align-items-center mb-2">
<div class="col-sm-2">
<b>Filter:</b>
</div>
<div class="col-sm-10">
<textarea class="form-control" rows="4" [(ngModel)]="c.filter"
name="channelFilter">
</textarea>
</div>
</div>
<div class="row align-items-center mb-2">
<div class="col-sm-2">
<b>Sources:</b>
</div>
<div class="col-sm-10">
<label *ngFor="let s of c.sources">
<input type="checkbox" [(ngModel)]="s.checked"
name="channelCheck">
{{ s.name }}
</label>
</div>
</div>
</div>
</div>
<div>
<button class="btn btn-success" type="submit" [disabled]="!f.valid">
Create profile
</button>
<button class="btn btn-default" (click)="d('reason')">Cancel</button>
</div>
</form>
提前感谢您的帮助
答案 0 :(得分:1)
我猜你正在寻找这个:name="{{'someName'+i}}"
。它将使用循环索引和一些名称缩进,最好是有意义的东西。
您还可以使用[name]="'someName' + i"
语法。
<div *ngFor="let c of profile.channels; let i=index">
<div class="row align-items-center mb-2">
<div class="col-sm-2">
<b>Name:</b>
</div>
<div class="col-sm-10">
<input type="text" [(ngModel)]="c.name" class="form-control" required
name="{{'someName'+i}}"
pattern="[a-zA-Z_][a-zA-Z_\-0-9]*" name="channelName">
</div>
</div>
....