Angular 如果屏幕在某个断点之上,显示一个 div,否则显示另一个
Angular if screen is above a certain breakpoint, show one div, else show another
在我的 html 上,我有两个布局不同的 div。
一个是一个table,一个是几个div
<div class="firstView>
<table class="table table-bordered">.....
..
<tr *ngFor="let data of Data">
<td>data.name</td>
</tr>
</table>
</div>
<div class="secondView">
<div class="col-md-12" *ngFor="let data of Data">
insert data here
</div>
我可以使用 show 和 hidden 在特定屏幕尺寸下显示或隐藏它们。
但是因为我在它们两个中都加载了数据,所以我认为最好有一个 If 语句,如果屏幕大小 > 992px 则显示和呈现 firstView
和 secondView 如果它小于那个。
如何使用断点作为值的 ngIf 语句?
如果你真的想使用 *ngIf 来摆脱 DOM 元素本身,你可以将 window.innerWidth
绑定到 ngOnInit
上的变量,然后有条件地使用它基于 *ngIf.
隐藏或显示容器
如果您还关心调整大小,您可以将主机侦听器绑定到 window 的调整大小事件,并在它触发时重新分配变量!
其实之前用的是旧帐号的回答,所以趁机在这里用正确的帐号详细说明一下!
因此,如果您想将 window 宽度保存到一个变量中,您可以像这样设置您的组件代码
class FooComponent implements OnInit {
public currentWindowWidth: number;
// ...
ngOnInit() {
this.currentWindowWidth = window.innerWidth;
}
// ...
}
在您的标记中,您可以简单地检查如下:
<div class="first" *ngIf="currentWindowWidth < 992">
...
</div>
<div class="second" *ngIf="currentWindowWidth >= 992" >
...
</div>
编辑:
如果您随后还想对调整大小做出反应,您可以按如下方式进行:
@HostListener('window:resize')
onResize() {
this.currentWindowWidth = window.innerWidth
}
在我的 html 上,我有两个布局不同的 div。 一个是一个table,一个是几个div
<div class="firstView>
<table class="table table-bordered">.....
..
<tr *ngFor="let data of Data">
<td>data.name</td>
</tr>
</table>
</div>
<div class="secondView">
<div class="col-md-12" *ngFor="let data of Data">
insert data here
</div>
我可以使用 show 和 hidden 在特定屏幕尺寸下显示或隐藏它们。 但是因为我在它们两个中都加载了数据,所以我认为最好有一个 If 语句,如果屏幕大小 > 992px 则显示和呈现 firstView 和 secondView 如果它小于那个。
如何使用断点作为值的 ngIf 语句?
如果你真的想使用 *ngIf 来摆脱 DOM 元素本身,你可以将 window.innerWidth
绑定到 ngOnInit
上的变量,然后有条件地使用它基于 *ngIf.
如果您还关心调整大小,您可以将主机侦听器绑定到 window 的调整大小事件,并在它触发时重新分配变量!
其实之前用的是旧帐号的回答,所以趁机在这里用正确的帐号详细说明一下!
因此,如果您想将 window 宽度保存到一个变量中,您可以像这样设置您的组件代码
class FooComponent implements OnInit {
public currentWindowWidth: number;
// ...
ngOnInit() {
this.currentWindowWidth = window.innerWidth;
}
// ...
}
在您的标记中,您可以简单地检查如下:
<div class="first" *ngIf="currentWindowWidth < 992">
...
</div>
<div class="second" *ngIf="currentWindowWidth >= 992" >
...
</div>
编辑:
如果您随后还想对调整大小做出反应,您可以按如下方式进行:
@HostListener('window:resize')
onResize() {
this.currentWindowWidth = window.innerWidth
}