0

I have a simple array tags = []; and I'm pushing blank element on addNew() using this.tags.push("");. It creates blank element in that array.

Now, I'm using this array to add multiple items to be added from the input

<div class="row tagEntry" *ngFor="let tag of tags, let i = index">
              <div class="col-md-10">
                <input type="text" name="tag-{{i}}" placeholder="Tag Name" [(ngModel)]="tag" class="form-control">
              </div>
              <div class="col-md-2">
                <button class="btn btn-block btn-danger" (click)="removeTag(i)"><i class="fa fa-trash"></i></button>
              </div>
            </div>

My TS file:

todoDesc: string = '';
  tags = [];

  ngOnInit() {
  }

  addTag () {
    this.tags.push("");
    console.log(this.tags)
  }

  removeTag (index) {
    this.tags.splice(index, 1);
  }

  addTodo () {
    console.log(this.todoDesc, this.tags)
  }

Issue here is, it is not binding the input and array two way. When I log the array after updating inputs, the array displays items with all blank value.

problem description

How to two way bind the array of elements in Angular 5 using *ngFor?

7
  • You can use FormArray or even QuerySelector to do that. The second way is more easy to understand Commented Nov 14, 2018 at 8:31
  • And your TS part please ? Commented Nov 14, 2018 at 8:32
  • @selemmn, updated the question Commented Nov 14, 2018 at 8:34
  • @FaizanSaiyed That is actually correct. tags array is a blank value array. Can you provide a sample at stackblitz. Commented Nov 14, 2018 at 8:36
  • @FaizanSaiyed and your addTag button in HTML :) Commented Nov 14, 2018 at 8:39

1 Answer 1

3

The issue is with Array whose changes are not being detected through reference. You can make the following changes -

html

<div class="row tagEntry" *ngFor="let tag of tags; let i = index; trackBy:trackIndex">
    <div class="col-md-10">
        <input type="text"  placeholder="Tag Name" [(ngModel)]="tags[i]" class="form-control">
              </div>
              <div class="col-md-2">
                <button class="btn btn-block btn-danger" (click)="removeTag(i)"><i class="fa fa-trash"></i></button>
              </div>
            </div>

ts

Add the following function in ts file. This function is very important otherwise the array will re-build the complete UI on any change and you will loose the focus from the elememt.

trackIndex(index,item){
  return index;
}

Here is the working copy - https://stackblitz.com/edit/angular-pzdw6s

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

Comments

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.