简体   繁体   中英

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

<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

EDIT2: Adding the initial picture on page load (green)

Solved the problem by using a uni-diractional binding {{}} and an index i . Thanks to @pero_hero for helping me find a simple solution!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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