@HostListener的Angular 4加载事件 [英] Angular 4 load event with @HostListener

查看:71
本文介绍了@HostListener的Angular 4加载事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我想要做的:

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']);
  }
}

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

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

问题与加载有关.我事件尝试 onload

The problem is with load. I event tried onload

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

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

我在这里想念什么?

推荐答案

在甚至初始化组件/指令之前,已经发生了 load 事件.

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

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

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.

这篇关于@HostListener的Angular 4加载事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆