Answer the question
In order to leave comments, you need to log in
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);
}
<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>
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();
}
<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>
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
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).
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 questionAsk a Question
731 491 924 answers to any question