简体   繁体   English

带有模板变量和双向绑定的角度形式 *ngfor

[英]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:描述:

  • Everything is shown with the last object value "profession" on init (model.overview : IOverview)一切都显示在 init 上的最后一个对象值“专业”(model.overview : IOverview)
  • Binding seems to work when I change it.当我改变它时,绑定似乎有效。
  • Template variable does not work it will be red (when any field is invalid) for all or green for all otherwise...模板变量不起作用,所有的都将是红色的(当任何字段无效时)或所有的绿色,否则......

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM