简体   繁体   中英

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.

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);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM