首页 > 解决方案 > 角 | 如何动态更改 ngTemplateOutlet 以实现响应目的

问题描述

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

我使用了很多ng-templatesfor 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>

标签: angularresponsive-designangular-flex-layout

解决方案


你可以尝试这样的事情:

@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>

推荐阅读