【问题标题】:Angular | How to dynamically change ngTemplateOutlet for responsive purpose角 |如何动态更改 ngTemplateOutlet 以实现响应目的
【发布时间】:2020-02-25 23:01:05
【问题描述】:

我正在使用带有Angular Flexbox 的Angular 来创建一个Web 应用程序。

我使用大量的ng-templates 用于多次使用的 html 代码块,以符合 DRY(不要重复自己)。

问题:是否可以根据屏幕宽度改变ngTemplateOutlet的值?

例子:

<ng-template #fullWidthContainer>
  <!-- code left out on purpose -->
</ng-template>

<ng-template #halfWidthContainer>
  <!-- code left out on purpose -->
</ng-template>

<!-- If width is less than medium: use 'fullWidthContainer', otherwise go with 'halfWidthContainer' -->
<ng-template [ngTemplateOutlet]="halfWidthContainer" [ngTemplateOutlet.lt-md]="fullWidthContainer"></ng-template>
<ng-template [ngTemplateOutlet]="halfWidthContainer" [ngTemplateOutlet.lt-md]="fullWidthContainer"></ng-template>

【问题讨论】:

    标签: angular responsive-design angular-flex-layout


    【解决方案1】:

    你可以试试这样的:

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

    在您的组件中监听窗口调整大小事件并获取窗口的宽度,然后根据该宽度您可以渲染您的 halfWidthContainer 或 fullWidthContainer。

    <!-- If width is less than medium: use 'fullWidthContainer', otherwise go with 'halfWidthContainer' -->
    <ng-template [ngTemplateOutlet]="(width < 300) ? fullwidthContainer : halfWidthContainer" ></ng-template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2021-04-12
      • 2022-01-21
      • 2017-09-20
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      相关资源
      最近更新 更多