简单的方法来检测点击子组件之外的区域
简单的方法来检测点击子组件之外的区域
我想根据一个变量的值来扩展和收缩子div
组件,但我也希望能够在该组件之外的地方(在父级或兄弟组件中)点击,以便将其折叠起来。
这里有一个stackblitz示例。我尝试使用HostListener
,根据我在这个问题中找到的内容,但它对我的情况没有帮助。
目标:
- 当我点击子组件(hello)时,如果它尚未展开,我希望它展开,如果已经展开,则收缩。
- 当我点击其他任何内容(例如父组件或兄弟组件)时,如果子组件(hello)已展开,我希望它收缩。
我不希望在点击父组件/兄弟组件时展开子组件(hello)。
更新:使用HostListener
hello.component.html
Hello.component
hello.component.ts
export class HelloComponent { isEnlarged = false; clicked() { this.isEnlarged = !this.isEnlarged; } @HostListener('document:click', ['$event']) documentClick(event: MouseEvent) { console.log('clicked'); this.isEnlarged = false; } }
app.component
export class AppComponent { }
问题是在单击处理程序设置expanded
为true之前,文档单击事件处理程序将其设置为false,因此它始终为false。
解决方法是只有当事件目标不是组件本身时,才将其设置为false。
代码如下:
('document:click', ['$event']) documentClick(event: MouseEvent) { console.log('clicked'); console.log(event); if (event.target.id !== 'box') { this.isEnlarged = false; } }
在HTML部分中没有设置任何ID,所以直到意识到这一点之前,它对我来说都不起作用!谢谢建议:-)