[英]Angular form *ngfor with template variable and two way binding
I have looked into several posts with this kind of problem but did not find a solution.我已经查看了几个有关此类问题的帖子,但没有找到解决方案。
description:描述:
html: html:
<div *ngFor="let item of objectKeys(model.overview)">
<div class="col form-group">
<label for="item">{{item}}</label>
<input type="text" class="form-control" id="item" required [(ngModel)]="model.overview[item]" name="item"
#inputmodel="ngModel" #spy>
<div [hidden]="inputmodel.valid || inputmodel.pristine" class="alert alert-danger">
{{spy.className}}
</div>
</div>
</div>
code:代码:
model = new Hero('uuid', this.overview);
objectKeys(obj) {
return Object.keys(obj);
}
Result Page load:结果页面加载:
Result when I edit some input fields:
当我编辑一些输入字段时的结果:
Where do I go wrong here?我哪里出错了?
EDIT1: Here is the resulting html: http://codebin.herokuapp.com?s=5e6e7688a569680004000006 EDIT1:这是生成的 html: http ://codebin.herokuapp.com?s=5e6e7688a569680004000006
EDIT2: Adding the initial picture on page load (green) EDIT2:在页面加载时添加初始图片(绿色)
Solved the problem by using a uni-diractional binding {{}}
and an index i
.通过使用
uni-diractional binding {{}}
和索引i
解决了该问题。 Thanks to @pero_hero for helping me find a simple solution!感谢@pero_hero 帮我找到了一个简单的解决方案!
Here is the final code:这是最终的代码:
<div *ngFor="let item of objectKeys(model.overview); let i = index">
<div class="col form-group">
<label for=item{{i}}>{{item}}</label>
<input type="text" class="form-control" id=item{{i}} required [(ngModel)]="model.overview[item]"
name=item{{i}} #inputmodel="ngModel" #spy>
<div [hidden]="inputmodel.valid || inputmodel.pristine" class="alert alert-danger">
{{spy.className}}
</div>
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.