anon
anon

Reputation:

Why Angular 4 does not detect Array.Filter change in NgFor?

I have this component in my project:

import { PromotionService } from './../promotion.service';
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { PromotionModel } from '../promotion.model';
import { AuthService } from '../../auth.service';

@Component({
  selector: 'app-list-promotion',
  templateUrl: './list-promotion.component.html',
  styleUrls: ['./list-promotion.component.scss'],
  providers: [PromotionService]
})
export class ListPromotionComponent implements OnInit {

  models : PromotionModel[] = [];

  @ViewChild('imageInput')
  imageInputElement : ElementRef;

  deletePromotion(model : PromotionModel) {
    this._promotionService.deletePromotion(model.id, this._authService.getToken())
      .subscribe(this.handleDeletePromotion.bind(this))
  }

  handleDeletePromotion(deletedModel : PromotionModel) {
    this.models = this.models.filter((model : PromotionModel) => {
      return model.id == deletedModel.id;
    });
  }
}

And the html is like below:

<div class="list-promotion-item" *ngFor="let model of models">
    <div class="list-promotion-item-action">
      <button class="button-link list-promotion-icon" (click)="deletePromotion(model)">Delete</button>
    </div>
  </div>

When I change the handleDeletePromotion with Array.splice it can update the array but if i use Array.filter like above it does not work. Why do we have this behavior in Angular 4?

Upvotes: 2

Views: 389

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

As per the code you implemented the logic should be :

return model.id != deletedModel.id; not return model.id == deletedModel.id;

Upvotes: 2

Related Questions