[英]How to use the Angular @HostListener onLoad to get the current width of the viewport?
我目前正在使用 Angular @HostListener来获取视口onResize()
的当前宽度,如下所示:
@HostListener('window:resize', ['$event'])
onResize(event?) {
window.innerWidth <= 400 ? this.width = 200 : this.width = 400;
}
但我还需要一种方法来设置组件的 this.width onLoad()
(在构造函数中或至少在ngOnInit()
生命周期中)。
我没有找到使用 HostListener 执行此操作的方法。 是否有一个很好的替代方法来获取视口的当前宽度(在调整大小和加载时)并对其做出反应?
我的目标是在移动视口尺寸上设置Leaflet-PopUp 的最大宽度。
如果您使用引导程序,则可以使用引导程序 CSS 媒体查询,
https://getbootstrap.com/docs/4.0/layout/overview/
否则,您尝试的方法是正确的,而无需使用外部依赖项。
simplay 你可以只调用它 selft 的方法,因为你不使用事件对象所以
ngOnInit() {
console.log(this.width);
this.onResize();
console.log(this.width);
}
如果您在构造函数中需要它,您可以注入DOCUMENT
内置令牌来获取document
。 它具有defaultView
属性,即当前window
或null
。 如果它不为null
你可以得到它的宽度:
constructor(@Inject(DOCUMENT) {defaultView}: Document) {
this.width = defaultView ? defaultView.innerWidth : 0;
}
...
clientWidth: number
initMethod() {
this.clientWidth = (document.childNodes[1] as any).clientWidth;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.