I have a simple function, checking the width of the window and according to that value it stretches the content. But when I resize the page and reload the site, nothing happens until I resize the window. How do I call a function on page load in angular2?
My whole appponent.ts
file:
import { Component } from '@angular/core';
@Component({
templateUrl: './appponent.html'
})
export class appComponent {
private checkScreenWidth() {
if (window.innerWidth < 1000 && window.innerWidth > 499) {
...
} else if (window.innerWidth < 500) {
...
} else {
...
}
}
}
I have a simple function, checking the width of the window and according to that value it stretches the content. But when I resize the page and reload the site, nothing happens until I resize the window. How do I call a function on page load in angular2?
My whole app.ponent.ts
file:
import { Component } from '@angular/core';
@Component({
templateUrl: './app.ponent.html'
})
export class appComponent {
private checkScreenWidth() {
if (window.innerWidth < 1000 && window.innerWidth > 499) {
...
} else if (window.innerWidth < 500) {
...
} else {
...
}
}
}
Share
Improve this question
edited Nov 26, 2016 at 22:37
jonrsharpe
122k30 gold badges268 silver badges476 bronze badges
asked Nov 26, 2016 at 22:34
J. DoeJ. Doe
611 gold badge1 silver badge6 bronze badges
4
-
3
Call it in
ngOnInit
orngAfterViewInit
? Have you read up on the lifecycle hooks? What have you tried? – jonrsharpe Commented Nov 26, 2016 at 22:35 - @jonrsharpe I just tried to call it in ponent, but didn't work as it supposed to. I will check on google ngOnInit and will let u know bout the progress. – J. Doe Commented Nov 26, 2016 at 22:36
- 2 angular.io/docs/ts/latest/guide/lifecycle-hooks.html – jonrsharpe Commented Nov 26, 2016 at 22:37
- @jonrsharpe It works, thank u. – J. Doe Commented Nov 26, 2016 at 22:40
2 Answers
Reset to default 2You may import and implement the OnInit
interface of angular2 core library and define its ngOnInit
method after implementing the interface in the class. I guess it will do the job.
export class appComponent implements OnInit {
private checkScreenWidth() {
if (window.innerWidth < 1000 && window.innerWidth > 499) {
...
} else if (window.innerWidth < 500) {
...
} else {
...
}
}
ngOnInit() {
this.checkScreenWidth();
}
}
First of all import OnInit from '@angular/core'module and then call a method inside ngOnInit which you want to call on load its like ng-init from angularjs.
import { Component, OnInit } from '@angular/core';
ngOnInit() {
this.checkScreenWidth();
}