Javascript 带有@HostListener 的 Angular 4 加载事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45131199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:55:40  来源:igfitidea点击:

Angular 4 load event with @HostListener

javascriptangular

提问by Jonathan Tugg

This is what I am trying to do:

这就是我想要做的:

import { Directive, HostListener, Input } from '@angular/core';

@Directive({
selector: '[appResizeWindow]'
})
export class ResizeWindowDirective {
@Input('appResizeWindow') line_ChartOptions: {};

constructor() { }

@HostListener('window:resize', ['$event']) onResize(event: Event) {
console.log('Yo');
if (event.target['innerWidth'] < 420)
  this.line_ChartOptions['hAxis']['format'] = 'MMM';
else if (event.target['innerWidth'] < 760)
  this.line_ChartOptions['hAxis']['format'] = 'MM. yy\'';
else this.line_ChartOptions['hAxis']['format'] = 'MMM d, yyyy';
}

@HostListener('load', ['$event']) onPageLoad(event: Event) {
   console.log('loaded');
   this.onResize(event.target['innerWidth']);
  }
}

So 'window.resize' works perfect when I attack in in the template.

因此,当我在模板中进行攻击时,'window.resize' 效果很好。

The problem is with load. I event tried onload

问题在于load。我事件尝试加载

I want the page to execute when the page is loaded.

我希望页面在加载时执行。

What am I missing here?

我在这里缺少什么?

采纳答案by Günter Z?chbauer

The loadevent has already happened before your component/directive is even initialized.

load事件在您的组件/指令甚至初始化之前就已经发生了。

Just add your code to ngAfterViewInit()If your component/directive is removed and re-added after it was first initialized, you need to take care yourself that the code isn't executed more than once by using a global service or a static variable to store the status.

只需将您的代码添加到ngAfterViewInit()如果您的组件/指令在首次初始化后被删除并重新添加,您需要注意代码不会通过使用全局服务或静态变量来存储多次执行地位。

回答by Sergi

i solved this using OnInit

我使用 OnInit 解决了这个问题

import { Directive, HostListener, Input, OnInit } from '@angular/core';

inside your component class put this..

在你的组件类里面放这个..

ngOnInit() {
  // Code to be executed on Init
}