1

I am new to Angular (5.x) and I am trying to bind the input value to string array (rule.values) at index (i) but when I change the input the array values do not change so I think binding fails. I appreciate any help or hint. Thank you

<div *ngFor="let _ of rule.value; let i = index;" id="values">
  <div class="row">
    <div class="col-sm-3">
      Value #{{(i + 1).toString()}}
    </div>

    <div class="col-sm-6">
      <input type="text" class="form-control" id="values{{i}}" [ngModel]="rule.value[i]" name="values{{i}}" required>
    </div>

    <div class="col-sm-3">
      <button type="button" class="btn btn-default" (click)="rule.value.splice(i, 1)">
        <span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
      </button>
    </div>
  </div>
</div>
1

1 Answer 1

5

when I change the input the array values do not change

You've only specified that whatever is in the model should reflected to the view by using [ngModel]="rule.value[i]". [] brackets show the "model -> view" relationship.

If you want to "catch" the value changes from the view to model, then you need to use the () brackets, too.

[(ngModel)]="rule.value[i]

This is a so-called "banana in the box" syntax since the ( resembles a banana and a [] is a box.

Using [] and () at the same time like this is basically a shortcut for writing both "model -> view" and "view -> model" bindings. The full version of the above code would be:

[ngModel]="rule.value[i]"
(ngModelChange)="rule.value[i] = $event"

By the way:

Value #{{(i + 1).toString()}}

You do not need to call .toString(), everything is automatically cast to a string when interpolated in a template.

Sign up to request clarification or add additional context in comments.

3 Comments

When I type the inputs, I think it keeps refreshing the DOM and I can only type one character at a time
Add ; trackBy: trackByIndex after let i = index in template (*ngFor part) and in your .ts file add a method trackByIndex (index: number) { return index }. This will stop the flicker you're experiencing.
No problems! Just a friendly reminder to accept the answer if it's what you were looking for -- it helps other see it as a correct solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.