angulariterationngforangular-template-variable

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:

<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: Result when I edit some input fields: result when I input some 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)


Solution

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