最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 4 load event with @HostListener - Stack Overflow

programmeradmin1浏览0评论

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.

The problem is with load. I event tried onload

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

What am I missing here?

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.

The problem is with load. I event tried onload

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

What am I missing here?

Share Improve this question asked Jul 16, 2017 at 17:00 Jonathan TuggJonathan Tugg 871 gold badge2 silver badges7 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 6

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

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.

try this one, this will work.

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

i solved this using OnInit

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

inside your component class put this..

ngOnInit() {
  // Code to be executed on Init
}
发布评论

评论列表(0)

  1. 暂无评论