Angular中可以使用@HostListener和HostBinding装饰器来获取和设置视口大小。
首先,在组件中导入这两个装饰器:
import { Component, HostListener, HostBinding } from '@angular/core';
接下来,在组件类中定义一个属性来存储视口的大小:
export class AppComponent { screenWidth: number; }
然后,使用HostListener装饰器监听窗口大小变化事件:
@HostListener('window:resize', ['$event']) onResize(event) { this.screenWidth = window.innerWidth; }
上面的代码会监听窗口大小变化事件,并将当前视口大小赋值给screenWidth属性。
最后,使用HostBinding装饰器将组件的样式绑定到screenWidth属性:
@HostBinding('style.background-color') get color() { return this.screenWidth < 768 ? '#eee' : '#cfd8dc'; }
上面的代码会根据当前视口大小设置背景颜色,当视口小于768px时,背景颜色为#eee,否则为#cfd8dc。
完成以上步骤后,就可以在Angular应用中获取和设置视口大小了。