我有一个简单的功能,检查窗口的宽度并根据该值拉伸(stretch)内容。但是当我调整页面大小时并重新加载网站时,在我调整窗口大小时之前没有任何反应。如何在 angular2 中调用页面加载函数?
我的整个 app.component.ts
文件:
import { Component } from '@angular/core';
@Component({
templateUrl: './app.component.html'
})
export class appComponent {
private checkScreenWidth() {
if (window.innerWidth < 1000 && window.innerWidth > 499) {
...
} else if (window.innerWidth < 500) {
...
} else {
...
}
}
}
最佳答案
您可以导入并实现angular2核心库的OnInit
接口(interface),在类中实现该接口(interface)后定义其ngOnInit
方法。我想它会完成这项工作。
export class appComponent implements OnInit {
private checkScreenWidth() {
if (window.innerWidth < 1000 && window.innerWidth > 499) {
...
} else if (window.innerWidth < 500) {
...
} else {
...
}
}
ngOnInit() {
this.checkScreenWidth();
}
}
关于javascript - 在页面加载时执行函数,ANGULAR 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40823824/