在 Angular 中使用正确的 CSS 媒体查询

新手上路,请多包涵

我读到在 Angular 中,使用 CSS 隐藏元素来隐藏这样的元素是一种非常糟糕的做法:

 .container{
  background-color : powderblue;
  height : 50px;
  width : 100%
}

@media (max-width: 400px){
    .container{
        display: none;
    }

}
 <div class="container"></div>

而且我知道显示或隐藏元素的 Angular 方法是使用 *ngIf 指令。

问题

如何让 * ngIf 以“角度方式”对媒体查询做出反应?

原文由 Willem van der Veen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 747
2 个回答

您可以使用 angular/breakpoints-angular-cdk

按着这些次序

在终端上

npm install @angular/cdk

然后导入布局模块并将其添加到 NgModule 的导入列表中

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 导入这些类

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;
        }
      });
  }
}

检查 文档 它是一个简单的 API

原文由 Vitor Kevin 发布,翻译遵循 CC BY-SA 4.0 许可协议

Angular flex 布局是更好的解决方案。您不需要媒体查询,它具有特殊的响应功能来显示和隐藏,例如

fxShow:此标记指定是否应显示(或不显示)其宿主元素

<div fxShow [fxShow.xs]="isVisibleOnMobile()"></div>

fxHide:此标记指定是否不应显示其宿主元素

<div fxHide [fxHide.gt-sm]="isVisibleOnDesktop()"></div>

无需编写大量 css,它与 angular 材质非常兼容。 https://github.com/angular/flex-layout

原文由 indrajeet 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题