【问题标题】:How do I route to a different angular page when the window size is below 800px?当窗口大小低于 800 像素时,如何路由到不同的角度页面?
【发布时间】:2020-01-17 10:06:18
【问题描述】:

我正在创建一个显示表格的 Angular 8 浏览器。由于有很多列,当窗口大小太小时,我想显示一个列较少的表格,可以向下扩展以显示更多信息。我已经在不同的 html 文件中创建了这两种不同的布局。有没有办法在屏幕达到一定大小后使用扩展行视图路由到文件,然后在屏幕足够大时使用常规表格视图路由回文件?这是怎么做到的?

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 我不会在窗口调整大小时路由到新页面。我会在您的父组件中收听窗口调整它的大小,然后使用 ngIf 或类似方法在大/小表格组件之间切换。对于在同一张表上真正删除/添加列的操作,导航似乎过大了。

标签: angular routing responsive


【解决方案1】:

您可以通过以下方式在父组件中使用BreakPointObserver加载合适的子组件。

import {BreakpointObserver} from '@angular/cdk/layout';

...

constructor(private bpo: BreakpointObserver){}

...

ngOnInit(){

    // Listen to changes in screen width
    this.bpo.observe(['(min-width: 800px)'])
    .subscribe(result => {
        if (result.matches) {
        // Navigate to larger view
        } else {
        // Navigate to smaller view
        }
    });
}

检查this StackBlitz 玩。更改输出窗口的屏幕大小,以查看 largersmaller 组件是否已相应加载。

编辑:

unsubscribe,需要在subscription上存储订阅和退订,比如-

private bpoSubscription: Subscription;

....

this.bpoSubscription = this.bpo.observe(['(min-width: 800px)'])
                       .subscribe(result => {
                         if (result.matches) {
                         // Navigate to larger view
                         } else {
                         // Navigate to smaller view
                         }
                        });

...

ngOnDestroy(){
   this.bpoSubscription.unsubscribe();
}

查看this updated Stackblitz

【讨论】:

  • 谢谢,这成功了!我如何让它只检查这个页面的最小宽度?它正在检查所有页面,并使用不同的视图选项导航到与此表无关的其他页面的较小视图。
  • 如果您来自附加在该特定组件的ngOnDestroy 中的侦听器unsubscribe,那应该可以解决问题。
  • 我收到此错误:core.js:6014 错误错误:未捕获(承诺中):NullInjectorError:StaticInjectorError(AppModule)[ListComponent -> Subscription]:StaticInjectorError(Platform:core)[ListComponent ->订阅]:NullInjectorError:没有订阅提供者! NullInjectorError: StaticInjectorError(AppModule)[ListComponent -> Subscription]: StaticInjectorError(Platform: core)[ListComponent -> Subscription]:
  • 在答案中更新。检查这是否适合您@BDev14
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 2018-09-10
  • 2022-01-05
相关资源
最近更新 更多