angular - 角 | 如何动态更改 ngTemplateOutlet 以实现响应目的
问题描述
我正在使用 Angular 和Angular Flexbox来创建一个 Web 应用程序。
我使用了很多ng-templates
for 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>
解决方案
你可以尝试这样的事情:
@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>
推荐阅读
- java - “错误:加载主类 src.Readability 时发生 LinkageError”编译和运行 Java 文件
- java - 如何避免在同一行打印两个连续的 System.out.prints?
- swift - 将数据从 UIViewControllerRepresentable 传递给 UIViewController
- c# - 如何创建不结束但等待事件的控制台应用程序?
- python - 无法在 Python 3 中组合两个字符串
- python - 为什么我不能将“对象”数据类型分配给包含所有“对象”类型条目的 Pandas 系列?
- python - PyQt5.QtWidgets 导致 tkinter 输入行中的退格问题
- angular - 我在尝试关闭对话框时遇到错误(dialog.close())
- reactjs - 向所有反应路线添加一个组件,但一个
- javascript - javascript中字符串迭代和连接的时间和空间复杂度