Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 756
user7513612 Avatar asked Oct 17 '22 19:10

user7513612


2 Answers

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>

like image 72
Cassiano Montanari Avatar answered Oct 21 '22 00:10

Cassiano Montanari


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>
like image 25
Neeraj Rathod Avatar answered Oct 21 '22 00:10

Neeraj Rathod