我正在使用angular-resize-event用于监听我的项目大小调整的工具。
所以我可以使用 <div (resized)="onResized($event)"></div>
监听任何元素
但我需要在嵌套组件中使用它来监听父级。
我正在使用我的ChartComponent
在我的WidgetComponent
初始化函数如下:
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);
}
关于javascript - 如何将自定义事件绑定(bind)到 Angular 中的父元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60448384/