gpt4 book ai didi

Angular 4如何在删除子组件中的项目后更新父组件

转载 作者:行者123 更新时间:2023-12-02 10:08:20 25 4
gpt4 key购买 nike

我在父组件(主组件)中有一个项目列表,当用户单击其中一个项目时,在同一页面的另一个组件(子组件/详细信息)中,它会显示所选项目的详细信息。我在子组件中有一个删除按钮,可以从数据库中删除所选项目。

我的问题是如何在删除子组件中的项目后更新父组件中的项目列表?

父组件:

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

子组件:

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

最佳答案

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()"

这样,当子项中的项目被删除时,就会在父项上调用 update()

关于Angular 4如何在删除子组件中的项目后更新父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44029362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com