Angular 5: Use ngClass to switch classes for mobile and desktop views

自闭症网瘾萝莉.ら 提交于 2020-01-15 10:46:08

问题


My application uses these classes: "large-screen" for desktop view and "small-screen" for mobile view. I am trying to use ngClass so I can switch between these classes in the container or wrapper div for various components but all of my implementations don't seem to work.

Requirement is to switch to "large-screen" for desktop view and switch to "small-screen" for mobile view. Below are the media queries already in place.

@media only screen and (max-width: 415px) {
  .large-screen {
    display: none;
  }
}
@media only screen and (min-width: 415px) {
  .small-screen {
    display: none;
  }
}

If anyone could suggest something different would be really appreciated.


回答1:


You could create only 1 class and change it's attributes depending on the media-queries, like this:

@media only screen and (max-width: 415px) {
  .class-name {
    background-color: blue;
  }    
}
@media only screen and (min-width: 415px) {
  .class-name {
    background-color: red;
  }
}

Otherwise you would have to display:none the classes in the media-queries you don't want them to appear, like this:

@media only screen and (max-width: 415px) {
  .small-screen {
    display: block;
  }
  .large-screen {
    display: none;
  }    
}
@media only screen and (min-width: 415px) {
  .small-screen {
    display: none;
  }
  .large-screen {
    display: block;
  }
}

This way you would have to use them both in all your divs that you want to work in both devices:

<div class="small-screen large-screen"></div>

If you want to use depending on a variable value, then the ngClass makes sense, you could use like this:

<div [ngClass]="{'small-screen': isMobile, 'large-screen': !isMobile}></div>




回答2:


You can achieve this by simple media query and class attribute of HTML. No need to go for ngClass.

CSS

@media only screen and (max-width: 415px) {
  .small-screen {
    display: block;
  }
  .large-screen {
    display: none;
  }
}
@media only screen and (min-width: 415px) {
  .small-screen {
    display: none;
  }
  .large-screen {
    display: block;
  }
}

Html

<div class="small-screen large-screen"></div>


来源:https://stackoverflow.com/questions/50052761/angular-5-use-ngclass-to-switch-classes-for-mobile-and-desktop-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!