在Angular中使用正确的CSS媒体查询 [英] Using proper CSS media queries in Angular
问题描述
我读到在Angular中,使用CSS
隐藏元素隐藏这样的元素是非常不好的做法:
I read that in Angular it is a very bad practice to use the CSS
hidden element to hide an element like this:
.container{
background-color : powderblue;
height : 50px;
width : 100%
}
@media (max-width: 400px){
.container{
display: none;
}
}
<div class="container"></div>
我知道显示或隐藏元素的Angular方法是使用*ngIf
指令.
And I know the Angular way to show or hide an element is using the *ngIf
directive.
我如何获得* ngIf
以角度方式"对媒体查询做出反应?
How can I get the * ngIf
to react on the media query in an 'Angular fashion'?
推荐答案
您可以使用angular/breakpoints-angular-cdk
You can use angular/breakpoints-angular-cdk
遵循这些步骤
在终端上
npm install @angular/cdk
然后导入布局模块并将其添加到NgModule的导入列表中
Then import the layout module and and add it to your NgModule’s list of imports
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { LayoutModule } from '@angular/cdk/layout';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
LayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
在您可以在组件中使用它之后,只需从@ angular/cdk/layout导入这些类
right after you can use it in your component, just import these classes from @angular/cdk/layout
import { Component, OnInit } from '@angular/core';
import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout';
@Component({ ... })
export class AppComponent implements OnInit {
public showContainer: boolean;
constructor(public breakpointObserver: BreakpointObserver) {}
ngOnInit() {
this.breakpointObserver
.observe(['(min-width: 400px)'])
.subscribe((state: BreakpointState) => {
if (state.matches) {
this.showContainer = true;
} else {
this.showContainer = false;
}
});
}
}
这篇关于在Angular中使用正确的CSS媒体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!