angular - 为组件的每个实例触发 Angular 事件处理程序
问题描述
我有一个页面(主机视图),我在其中动态创建包含信息的组件,包括用户在 UI 中创建的 p-tree。我使用主机视图中的按钮添加它们,并使用树组件上的按钮删除它们,该按钮通过通知服务将事件传递回主机视图,如下所示:
在主机视图中创建:
constructor(@Inject(Loader) service, @Inject(ViewContainerRef) viewContainerRef, public dataCenter: DataCenterService,private router: Router) {
this.service = service;
this.trees = this.dataCenter.getTreeState();
this.service.setRootViewContainerRef(viewContainerRef)
this.newTree();
}
newTree() {
var newTree = this.service.addDynamicComponent();
newTree.instance.ref = newTree;
newTree.instance.service.onDestroyEvent.subscribe(
treeRef => {
for(var i=0;i<this.trees.length; i++){
if(this.trees[i].instance.ref == treeRef){
this.trees.splice(i,1);
}
}
}
);
this.trees.push(newTree);
}
通知服务:
export class NotificationService {
onDestroyEvent: EventEmitter<ComponentRef<ConnectionTreeComponent>> = new EventEmitter();
constructor() {}
}
树组件:
服务:通知服务;
constructor(public dataCenter: DataCenterService, public treeService: TreeDragDropService, service:NotificationService) {
this.service = service;
}
ngOnDestroy() {
this.service.onDestroyEvent.emit(this.ref); /*ComponentRef passed back to hostview*/
}
所以这在技术上确实有效,但它为树组件的每个实例调用一次,而不仅仅是一次。我该如何解决这个问题才能正常工作?
解决方案
我删除了 NotificationService 并将 onDestroyEvent 放入树组件中,并进行了相应的重构。这解决了重复事件问题。
推荐阅读
- php - 搜索 3 个日期范围之间的记录
- mysql - MariaDB UNIX_TIMESTAMP() 在未来使用日期时返回 NULL
- firebase - 错误:无法使用 Swift 5 构建 Objective-C 模块“Firebase”
- stormcrawler - 带有 ES 的 Stormcrawler - 内容未存储
- html - 有效地流式传输具有大静音间隙的音频
- swift - 在 Swift 5 中遇到 while 循环问题
- android - 我应该将哪个类用于每日通知/提醒 - AlarmManager、JobScheduler、WorkManager?
- maven - 为什么我不能更改项目 facet 的版本?
- python - 如何在 Pandas 中对日期时间列使用条件逻辑?
- javascript - 如何让 mouseenter 函数显示数据