iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0
自我挑戰組

Angular 元件煉成練習計畫系列 第 5

螢幕寬度的廣播

  • 分享至 

  • xImage
  •  

構想完才發現 CDK layouts 處理了 元件內是不是符合尺寸區間的想法
然後發現基本上是拉機
沒有合理的使用情境
糗爛/images/emoticon/emoticon06.gif

export class Day5PageComponent {
  signalIsSmall: Signal<boolean | undefined>
  private breakPoint = inject(BreakpointObserver)

  constructor() {
    this.signalIsSmall = toSignal(
      this.breakPoint.observe(Breakpoints.Small).pipe(
        tap((res) => console.log(res)),
        //   {
        //     "matches": true,
        //     "breakpoints": {
        //         "(min-width: 600px) and (max-width: 959.98px)": true
        //     }
        // }
        map((res) => {
          return !!(res.matches)
        })
      )
    )
  }
}

在不同的地方接收中央控制告知現在的螢幕尺寸

定義尺寸


export const isSizeS = (screenWidth: number): boolean => {
  return screenWidth <= 767
}

export const isSizeM = (screenWidth: number): boolean => {
  return screenWidth > 767 && screenWidth <= 1219
}

export const isSizeL = (screenWidth: number): boolean => {
  return screenWidth > 1219
}

export enum ScreenSize {
  S = 's',
  M = 'm',
  L = 'l',
}

type fn = (screenWidth: number) => boolean
export const sizeRecord: Record<ScreenSize, fn> = {
   [ScreenSize.S]: isSizeS ,
   [ScreenSize.M]: isSizeM ,
   [ScreenSize.L]: isSizeL,
}

resize事件

  @HostListener('window:resize', ['$event'])
  onResize($event:any) {
    console.log($event.target.innerWidth)
  }

不知道為啥會想放service 撞到頭

export class Day5PageComponent {

  public signalWidth: WritableSignal<ScreenSize | null> = signal<ScreenSize | null>(null)

  resize = inject(BroadcastWidthService)

  @HostListener('window:resize', ['$event'])
  onResize($event: any) {
    const screenWidth = $event.target.innerWidth
    switch (true) {
      case sizeRecord[ScreenSize.S](screenWidth):
        this.signalWidth.set(ScreenSize.S)
        break
      case sizeRecord[ScreenSize.M](screenWidth):
        this.signalWidth.set(ScreenSize.M)
        break
      case sizeRecord[ScreenSize.L](screenWidth):
        this.signalWidth.set(ScreenSize.L)
        break

    }
  }
}

上一篇
在material accordion 在外掛一個收合功能
下一篇
line pay
系列文
Angular 元件煉成練習計畫12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言