【问题标题】:Angular 4 How to update parent component after delete an item in child componentAngular 4删除子组件中的项目后如何更新父组件
【发布时间】:2017-10-17 04:22:34
【问题描述】:

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

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

父组件:

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

【问题讨论】:

  • 您使用的是哪个 Angular 版本?请添加演示您尝试完成的代码。
  • 对不起,我的版本是 angular 4,我在代码中添加了所有细节。

标签: angular parent


【解决方案1】:
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() 会在子级中删除项目时在父级上调用。

【讨论】:

  • 我错过了将 null 传递给 emit 函数,我头晕目眩。你的回答很有魅力。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2021-02-10
  • 2018-03-15
  • 1970-01-01
  • 2012-09-18
  • 2018-11-19
  • 2018-07-15
相关资源
最近更新 更多