0
votes

I have an Angular parent component that creates an array containing several child components based on a value (e.g., 1 ParentComponent creates 10 ChildComponents). The ChildComponent has HTML that displays several buttons, including a delete button. The delete button while make the child component delete itself.

After deleting a ChildComponent, how should I go about notifying the parent of the change? After the deletion the parent still contains the deleted object in it's ChildComponents array. I've seen posts about using an Output EventEmitter, but is it possible to do this without an EventEmitter?

1
If you don't want to use EventEmitter, you can pass callback functions into child components just using @InputFrank Modica
How are you making the child component delete itself? Normally components are not able to control their lifecycle. Usually it's the parent's responsibility, so an EventEmitter is the best solution.joh04667
Are you using ngFor to create the array?Ben
@Ben Yes, I am using an ngFor.Roka545

1 Answers

2
votes

If you use an ngFor directive to create the loop of child components, you should be able to directly call a delete method from the parent. For example:

HTML

<div *ngFor="let item of items; index as i;">
  <div>{{name}}</div>
  <button (click)="delete(i)"></button>
</div>

Component

import { Component } from "@angular/core";

@Component({
  selector: "app",
  templateUrl: "./app.html",
})
export class AppComponent {    
  public items = [{name: "first"}, {name: "second"}];

  public delete(index: number) {
    this.items.splice(index, 1);
  }
}

Each child component can directly call the delete method from the parent and then use the index to indicate which item in the list should be removed.