0

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

Ben Ari Kutai
  • 509
  • 3
  • 9
rufreakde
  • 542
  • 4
  • 17
  • could you add the resulting htm to the op? – pero_hero Mar 15 '20 at 17:15
  • So, you are not able to apply the alert class conditionally? – ngShravil.py Mar 15 '20 at 17:32
  • Tha altert div seems not the have a "unique" scoped tempalte variable attached to it... (kinda merged) And the values in the Input fields are alwas "profession" even though when I type something in it is correctly set. @pero_hero what do you mean htm? do you mean html? I cann add that. – rufreakde Mar 15 '20 at 18:38
  • could you try to use an index in your *ngFor in order to have unique ids? `*ngFor="let item of objectKeys(model.overview); let i = index"` and id="'item'+i" – pero_hero Mar 15 '20 at 19:57
  • The IDs are now unique: I used `for=item{{i}}` and `id=item{{i}}` https://pastiebin.com/5e6e901acaca9 But the problem with the alert and the wrongly initialized form persists still... – rufreakde Mar 15 '20 at 20:31
  • edditing`name=item{{i}}` did the trick! Nice! I will update this with an answer :) – rufreakde Mar 15 '20 at 20:33

1 Answers1

0

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>
rufreakde
  • 542
  • 4
  • 17