Node.JS
Node.JS

Reputation: 1570

Angular - Binding to string array at index

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>

Upvotes: 1

Views: 1932

Answers (1)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19754

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.

Upvotes: 5

Related Questions