0

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?

Roka545
  • 3,404
  • 20
  • 62
  • 106

1 Answers1

2

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.

Auqib Rather
  • 396
  • 1
  • 10
Ben
  • 960
  • 8
  • 17