K
K
kikosko2018-10-03 14:50:49
Angular
kikosko, 2018-10-03 14:50:49

Why doesn't the UI update when an element is removed?

I send the post ID from the child component to the parent component, where I call the service to remove the element, I checked in the console, the elements are deleted, but the changes are not visible in the interface. In the deletion method, after a request to the service, I re-receive posts.
Please help me solve this problem and understand what I'm doing wrong in the
TS of the child component:

@Output() remove: EventEmitter<number> = new EventEmitter();

    removePost(picId: number): void {
        this.remove.emit(picId);
    }

Child component template:
<img [src]="pic.url" alt="test" class="img-responsive">
<p class="lead"><span>{{pic.id}}:</span>{{pic.title}}</p>
<div class="card buttons">
    <button class="btn btn-danger del" (click)="removePost(pic.id)">Delete</button>
</div>

TS of the parent component:
export class GalleryComponent implements OnInit {
    collection: Picture[];
    constructor(private galleryService: GalleryService) {}

    ngOnInit() {
        this.collection = this.galleryService.getPictures();
    }

    removePost(picId: number): void {
       this.galleryService.remove(picId);
       this.collection = this.galleryService.getPictures();
    }

Parent component template:
<div class="col-lg-3 col-md-4 col-6" *ngFor="let pic of collection">
        <app-gallery-item [pic]="pic" (remove)="removePost($event)" (edit)="editPost($event)"></app-gallery-item>
    </div>

Service:
import { Injectable } from '@angular/core';
import { myCollection } from  './gallery-data';
import {Picture} from "./gallery-module/gallery/Picture";

@Injectable({
  providedIn: 'root'
})
export class GalleryService {
  Mycollection: Picture[] = myCollection;
  constructor() { }

  getPictures(): Picture[]  {
    return (myCollection);
  }
  remove(picId: number): Picture[] {
   return this.Mycollection  = this.Mycollection .filter(p => p.id !== picId);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-10-03
@kikosko

After deleting the element, you ask for the original data - the getPictures method instead of this.Mycollection returns myCollection (by the way, was there any way to think of normal names? - without this ugly my and so that uppercase is used more, mmm, uniformly).

D
Dasha Tsiklauri, 2018-10-03
@dasha_programmist

you have a service because it always returns the same collection, but this.Mycollection should

getPictures(): Picture[]  {
    return (myCollection);
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question