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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With