Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set different css class based on screen size in Angular?

I have this floating button in my Angular Application,

  <button [ngClass]="{
  'mdc-fab--extended': extendedClass,
  'mdc-fab--mini': miniClass
}" class="mdc-fab mdc-fab--touch    ">
<div class="mdc-fab__ripple"></div>
<span class="material-icons mdc-fab__icon">mail</span>
<!-- <span class="floating-span">My Invite Link</span> -->
<div class="mdc-fab__touch"></div>

And I need to change the mdc-fab–extended className to mdc-fab–mini when screen size is 768px or lower?
What can I do to achieve this functionality?
Thanks

I’ve tried this but the classes are not being removed/added

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    if (window.innerWidth < 768) {
  this.miniClass = true;
  this.extendedClass = false;
} else {
  this.miniClass = false;
  this.extendedClass = true;
}

>Solution :

You can add hostlistener to your component.

public size700_1020 = false;
public size400_700 = false;

@HostListener('window:resize', ['$event'])
onResize(event) {
   alert(window.screen.availWidth);
   alert(window.screen.availHeight);

   if(window.innerWidth < 700 && window.innerHeight < 1020) {
       // now based on the screen size you want to check 
       // enable the variable and make it true
       // based on it, you can enable the class in template
   } 
}

In template:

<div class="size700_1020 ? 'addThisClass' : 'elseThis'"></div>

There are multiple properties for your requirement on window object. I am attaching some links which might give you more ways here1 and here2.

You can also do this.

import { Platform } from 'ionic-angular';

...
private width:number;
private height:number;

constructor(private platform: Platform){
    platform.ready().then(() => {
        this.width = platform.width();
        this.height = platform.height();
    });
}

As per the changes made in the question:

  <button [ngClass]="miniClass ? 'addMiniClass':'extendedClass'" class="mdc-fab mdc-fab--touch    ">
<div class="mdc-fab__ripple"></div>
<span class="material-icons mdc-fab__icon">mail</span>
<!-- <span class="floating-span">My Invite Link</span> -->
<div class="mdc-fab__touch"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading