Reputation: 727
I have a list of items in parent component (master) and when user clicks one of the items, in another component (child / details) on same page it shows details of the selected item. I have a delete button in child component which deletes the selected item from database.
My question is how can I update list of items in parent component after deleting an item in child component?
Parent Component:
export class ProjectListComponent implements OnInit {
projects : Project[];
selectedProject: Project;
constructor(private _projectService: ProjectService) { }
ngOnInit() {
this.projects = [];
this.fetchListOfProjects();
}
fetchListOfProjects(){
this._projectService.getProject()
.subscribe(projects => {
this.projects = projects;
})
}
onSelect(project: Project): void {
this.selectedProject = project;
}
}
Child Component:
export class ProjectItemComponent implements OnInit {
@Input() project: Project;
constructor(private _projectService:ProjectService) { }
ngOnInit() { }
onDelete(id:any){
if(confirm("Are you sure to delete the project?")) {
this._projectService.deleteProject(id)
.subscribe(result =>{
if(result.status == 204){
console.log('removed');
};
});
}
}
}
Upvotes: 3
Views: 2949
Reputation: 657078
export class ProjectItemComponent implements OnInit {
@Input() project: Project;
constructor(private _projectService:ProjectService) { }
@Output()
someEvent = new EventEmitter();
ngOnInit() { }
onDelete(id:any){
if(confirm("Are you sure to delete the project?")) {
this._projectService.deleteProject(id)
.subscribe(result =>{
if(result.status == 204){
console.log('removed');
this.someEvent.emit(null);
};
});
}
}
<project-item (someEvent)="update()"
This way update()
is called on the parent, when an item is deleted in the child.
Upvotes: 5