Home > Software design >  How to set different css class based on screen size in Angular?
How to set different css class based on screen size in Angular?

Time:11-12

I have this floating button in my Angular Application,

  <button [ngClass]="{
  'mdc-fab--extended': extendedClass,
  'mdc-fab--mini': miniClass
}" >
<div ></div>
<span >mail</span>
<!-- <span >My Invite Link</span> -->
<div ></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

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

CodePudding user response:

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 ></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'" >
<div ></div>
<span >mail</span>
<!-- <span >My Invite Link</span> -->
<div ></div>

CodePudding user response:

Component.ts

    classFlag = false;
    ngOnInit(){
     if (screen.width <= 768) {
      this.classFlag = true;
    } else {
      this.classFlag = false;
    } 
  }

HTML

<button 
  [ngClass]="classFlag ? 'mdc-fab--extended' : 'mdc-fab--mini'">
</button>

try screen.width instead of window.innerWidth

CodePudding user response:

Component :

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

HTML :

<button 
  [ngClass]="classFlag ? 'mdc-fab--extended' : 'mdc-fab--mini'">
</button>

Triggering on RESIZING WINDOW OR BROWSER Check this : https://stackoverflow.com/a/49917082/11492378

  • Related