javascript - 如何以角度将自定义事件绑定到父元素?
问题描述
我正在使用angular-resize-event工具来收听我的项目的大小调整。
所以我可以听任何元素使用<div (resized)="onResized($event)"></div>
但我需要在我的嵌套组件中使用它来监听父级。
我ChartComponent
在我的WidgetComponent
init 函数中使用我的,如下所示:
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
事件?
解决方案
如果您希望您的子组件从父组件监听,您可以使用 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);
}
推荐阅读
- json - fluentd 中的 JSON 解析错误,总是抛出不匹配的模式
- java - 如何将 2 个 hashmap 组合成 1 个
- javascript - 当孩子有类jquery时添加类
- ios - 尝试访问私有依赖项时,开发中的私有 cocoapod 无法 lint
- python - selenium.common.exceptions.WebDriverException:消息:未知错误:无法聚焦元素,slenium
- npm - 尝试在终端中安装 nodemon 并失去与 npm 的连接
- python - sklearn OneHotEncoding 与 ColumnTransformer
- java - 是否可以加入两个 Java 8 流?
- docker - 正确使用 node-red 的 docker volume
- c++ - 有没有办法检查 CMakeLists 文件中是否有未使用的包?