简体   繁体   中英

Angular 2 deleting of selected item of an array in Child component

I have an array of elements and each array item has one Delete link on click of which I want the selected array item to be deleted. I am pushing the objects into the array already and able to get the data.

The code I am using is mentioned below.

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

My Parent component-

@Component({
  selector: 'child',
  template: `
    <div>
      <child *ngFor="let element of elements; let i= index;" [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);
    }
  }

Right now, every time the last item of the array is getting deleted instead of deleting the selected item.For ex. If i click on Delete link for the 0th or 1st index, still the last item is being deleted. I am not sure where I am going wrong.

EDIT: well, you can also do it this way:

You need to pass which element is to be deleted, so that the right element will be deleted. So change your code a bit, below pass the element in your delete.

<div>
  {{element.name}}
  <span (click)="deleteElement(element)">Delete</span> 
</div>

and make your emit pass the element to be deleted:

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

and then delete the element:

onElementDeleted(element) {
  let index = this.elements.indexOf(element);
  this.elements.splice(index, 1);
}

And as mentioned by Daniel, # is deprecated, use let instead.

Please update your Angular2 version. The problem here is probably with the removed syntax *ngFor=#element of elements , where the #element is changing after assignments, so you get the last element from the list in every case (template global scope). New syntax is *ngFor="let element of elements" and it works fine. Plunker: https://plnkr.co/edit/OsxUS3V5pB3Tqko5SojJ?p=preview

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