首页 > 解决方案 > 如何以角度将自定义事件绑定到父元素?

问题描述

我正在使用angular-resize-event工具来收听我的项目的大小调整。

所以我可以听任何元素使用<div (resized)="onResized($event)"></div>

但我需要在我的嵌套组件中使用它来监听父级。

ChartComponent在我的WidgetComponentinit 函数中使用我的,如下所示:

ChartComponent 的 init 函数是:

ngOnInit() {
     let chartComponent = this.elementRef.nativeElement.parentElement;
     let widgetContainerComponent = chartComponent.parentElement;
     let cardBody = widgetContainerComponent.parentElement;

     this.renderer.listen(cardBody, 'resized', (event) => {
       console.log(event)
    })
}

但这不起作用。但是如果我添加点击监听器,它就可以工作。

    this.renderer.listen(cardBody, 'click', (event) => {
       console.log(event)
    })

我想resized从子组件监听父事件。如果父尺寸发生变化,我将在子组件(ChartComponent)中设置图表的宽度和高度。

如何设置resized事件?

标签: javascriptangularangular8

解决方案


如果您希望您的子组件从父组件监听,您可以使用 EventEmitter。一个例子;

在您的子组件上添加一个 EventEmitter:

@Input() private uploadSuccess: EventEmitter<boolean>;

另外在 childComponent.ts 中订阅事件:

ngOnInit() {
  if (this.uploadSuccess) {
   this.getEvent.subscribe(data => {
     // Do something in the childComponent after parent emits the event.
   });
  }
}

父组件

在 ParentComponent.html 中

<child-component  [uploadSuccess] = "uploadSuccess" > </child-component>

在 ParentComponent.ts

private uploadSuccess: EventEmitter<boolean> = new EventEmitter();

  onImageUploadSuccess(event) {
    console.log('Image Upload succes');
    if (event.code === 'OK' && this.maxUploadLimit > 0) {
      this.galleryImagesCount = this.galleryImagesCount + 1;
      this.maxUploadLimit = this.maxUploadLimit - 1;
     }

      // The parent emits the event which was given as `@Input` variable to the child- 
   component
     this.uploadSuccess.emit(true);
   }

推荐阅读