Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 child component deleting

I have an angular application, and I'm having an issue. I have a (parent) component that has an array of items, for each item there is a sub (child) component. The child components each have a button (and function) to delete themselves, but the parent component is not being notified of this event taking place.

I'm not sure what is the proper way to delete the child component in such away that the parent component removes it from the view. I am currently just calling delete this.product (product is one of the items in the parent array) which does indeed remove it from the parent array, but the parent array does not update.

like image 800
Gabe O'Leary Avatar asked Jan 06 '23 07:01

Gabe O'Leary


1 Answers

You could implement this this way in the child component:

@Component({
  selector: 'child',
  template: `
    <div>
      {{element.name}}
      <span (click)="deleteElement()">Delete</span>
    </div>
  `
})
export class ChildComponent {
  @Input()
  element: any;
  @Output()
  elementDeleted: EventEmitter<any> = new EventEmitter();

  deleteElement() {
    this.elementDeleted.emit();
  }
}

And leverage this event in the parent:

@Component({
  selector: 'child',
  template: `
    <div>
      <child *ngFor="#element of elements" [element]="element"
             (elementDeleted)="onElementDeleted(element)">
      </child>
    </div>
  `
})
export class ParentComponent {
  constructor() {
    this.elements = [
      { name: 'element1' },
      { name: 'element2' },
      (...)
    ];
  }

  onElementDeleted(element) {
    var index = this.elements.findIndex((elt) => (elt===element));
    if (index != -1) {
      this.elements.splice(index, 1);
    }
  }
like image 61
Thierry Templier Avatar answered Jan 15 '23 20:01

Thierry Templier