Answer the question
In order to leave comments, you need to log in
How to correctly implement the removal of an element in a child component?
I want to implement the removal of an element in a child component and pass the @ Output decorator to the parent component, but I get an error, tell me how to do it right?
Parent template:
<div class="row" *ngIf="toggle">
<div class="col-lg-3 col-md-4 col-6" *ngFor="let pic of collection">
<app-gallery-item [pic]="pic" (remove)="removePost($event)"></app-gallery-item>
</div>
</div>
import {Component, OnInit} from '@angular/core';
import {Picture} from './Picture'; // interface
import {myCollection} from '../gallery-data'; // data
@Component({
selector: 'app-gallery',
templateUrl: './gallery.component.html',
styleUrls: ['./gallery.component.css']
})
export class GalleryComponent implements OnInit {
collection = myCollection;
constructor() {}
}
<img [src]="pic.url" alt="test" class="img-responsive">
<p class="lead"><span>{{pic.id}}:</span>{{pic.title}}</p>
<div class="del">
<button class="btn btn-outline-danger" (click)="removePost(pic.id)">Delete</button>
</div>
import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import { Picture } from '../Picture';
@Component({
selector: 'app-gallery-item',
templateUrl: './gallery-item.component.html',
styleUrls: ['./gallery-item.component.css']
})
export class GalleryItemComponent implements OnInit {
@Input() pic:Picture;
@Output() remove: EventEmitter<any> = new EventEmitter();
constructor() { }
removePost(pic: number) {
this.collection = this.collection.filter(p => p.id !== pic);
this.remove.emit();
}
}
Answer the question
In order to leave comments, you need to log in
Why is an element removed in a child component that does not know about any collection? Why does the parent component specify a non-existent method as an event handler?
Probably, the removePost method from the child component should be divided into two: removePost in the child component emits the id of the element, and removePost in the parent component by this id removes the element from the array. That is, in the child:
removePost(picId: number) {
this.remove.emit(picId);
}
removePost(picId: number) {
this.collection = this.collection.filter(p => p.id !== picId);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question