带窗口宽度的侧边栏角度切换

时间:2019-11-27 14:35:44

标签: angular

我遇到一个问题,我的侧边栏处于折叠状态。 哪个是通过以下方式触发的is-collapsed类:

<div class="app"
     [ngClass]="{'is-collapsed': collapsedMenuState}">

我有一些手动触发器,例如:

 <div class="mobile-toggle sidebar-toggle"
                 (click)="collapsedMenuState = !collapsedMenuState">
              <a href=""
                 class="td-n">
                <i class="ti-arrow-circle-left"></i>
              </a>
            </div>

和:

<li>
          <a id='sidebar-toggle'
             class="sidebar-toggle"
             (click)="collapsedMenuState = !collapsedMenuState">
            <i class="ti-menu"></i>
          </a>
        </li>

这些开关工作正常,但是我希望在某些断点处保持动态。

因此在组件上,我创建了一个监听器,例如:

export class BasicLayoutComponent implements OnInit, AfterViewInit, OnDestroy {
  collapsedMenuState: boolean;
  version: string;
  readonly widthBreakpoint: number = 1440;
  private resizeSub$: Subscription;
  private windowSize: Subject<number> = new BehaviorSubject(0);

  constructor(private router: Router,
    private cdRef: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.version = environment.VERSION;
    this.resizeSub$ = this.windowSize.pipe(
      filter(size => size > 0)
    ).subscribe(size => {
      this.isSidebarCollapsable(size);
      this.cdRef.detectChanges(); // if I don't use this I get an ExpressionChangedAfterItHasBeenCheckedError
    });
  }

  ngAfterViewInit() {
    this.windowSize.next(window.innerWidth);
  }

  ngOnDestroy() {
    this.resizeSub$.unsubscribe();
  }

  @HostListener('window:resize', ['$event'])
  private onResize(event) {
    this.windowSize.next(event.target.innerWidth);
  }

  isSidebarCollapsable(windowWidth: number) {
    if (windowWidth < this.widthBreakpoint) {
      this.collapsedMenuState = true;
    } else {
      this.collapsedMenuState = false;
    }
    console.log(windowWidth, this.collapsedMenuState);
  }

  goToLogin() {
    this.router.navigate([`/${urls.LOGIN}`]);
  }

}

此方法以及其他一些方法似乎无效。注意console.log(windowWidth, this.collapsedMenuState),它记录了正确的语句,但是侧边栏保持不变(打开)。如果将默认宽度更改为小于断点,则增加默认宽度以触发更改即可,但是反之则不行。

任何提示我应该去哪里? 诗:我不!希望为如此小的行为提供单独的服务。

1 个答案:

答案 0 :(得分:0)

请您检查一下这个工作示例吗?

 private resizeSub$: Subscription;

  constructor(private router: Router,
    private cdRef: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.version = environment.VERSION;
  }

  ngAfterViewInit() {
    this.isSidebarCollapsable(window.innerWidth);
    this.resizeSub$ = fromEvent(window, 'resize').pipe(debounceTime(300))
      .subscribe(_ => {
        this.isSidebarCollapsable(window.innerWidth);
      });

  }

  ngOnDestroy() {
    this.resizeSub$.unsubscribe();
  }

  isSidebarCollapsable(windowWidth: number) {
    if (windowWidth < this.widthBreakpoint) {
      this.collapsedMenuState = true;
    } else {
      this.collapsedMenuState = false;
    }
    console.log(windowWidth, this.collapsedMenuState);
  }