@kikosko

Как правильно реализовать удаление элемента в дочернем компоненте?

Хочу реализовать удаление элемента в дочернем компоненте и передать декоратором @ Output в родительский, но получаю ошибку, подскажите как сделать правильно ?
Родительский темплейт:
<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();
  }
}
  • Вопрос задан
  • 195 просмотров
Решения вопроса 1
0xD34F
@0xD34F
Почему удаление элемента осуществляется в дочернем компоненте, который ни про какую collection знать не знает? Почему в родительском компоненте в качестве обработчика события указывается несуществующий метод?

Наверное, метод removePost из дочернего компонента надо разделить на два: removePost в дочернем компоненте эмитит id элемента, а removePost в родительском компоненте по этому id осуществляет удаление элемента из массива. Т.е., в дочернем:

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

В родительском:

removePost(picId: number) {
  this.collection = this.collection.filter(p => p.id !== picId);
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы