監聽視窗調整大小事件的元件

假設我們有一個隱藏在某個視窗寬度的元件。

import { Component } from '@angular/core';

@Component({
  ...
  template: `
    <div>
      <p [hidden]="!visible" (window:resize)="onResize($event)" >Now you see me...</p>
      <p>now you dont!</p>
    </div>
  `
  ...
})
export class MyComponent {
  visible: boolean = false;
  breakpoint: number = 768;

  constructor() {
  }
  
  onResize(event) {
    const w = event.target.innerWidth;
    if (w >= this.breakpoint) {
      this.visible = true;
    } else {
      // whenever the window is less than 768, hide this component.
      this.visible = false;
    }
  }
}

visible 為假時,我們模板中的 p 標籤將隱藏。每當呼叫 onResize 事件處理程式時,visible 都會改變值。每次 window:resize 發生事件時都會發出呼叫。