Home > database >  Show warning if user's browser width is less than x
Show warning if user's browser width is less than x

Time:03-10

I have an Angular application which is best viewed in resolution higher than 1600 x 900.

Is there anyway I can automatically show a warning message to the user if user is trying to view the application with less than 1600 width (either in restored mode or using lower resolution)? If possible, using bootstrap css.

CodePudding user response:

yes you can get the screen width using window object

inside your onInit in TS

  import { HostListener } from '@angular/core';
  public innerWidth: any;
  ngOnInit() {
    this.innerWidth = window.innerWidth;
  }
  @HostListener('window:resize', ['$event'])
  onResize(event) {
  //you'll get the width
    this.innerWidth = window.innerWidth;
    console.log('this.innerWidth', this.innerWidth);
  }

Add your warning code inside onResize or handle accordingly.

CodePudding user response:

We use hostlistener to check window size during resize, but we also check width on component init ngOnInit() because component might start without resize event.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  host: {
    '(window:resize)': 'onWindowResize($event)',
  },
})
export class AppComponent implements OnInit {
  name = 'Angular';
  width: number = window.innerWidth;
  height: number = window.innerHeight;
  goodWidth: number = 1600;

  ngOnInit(): void {
    this.getInitSize();
  }

  getInitSize() {
    this.width = window.innerWidth;
    this.height = window.innerHeight;
    this.shouldAlert();
  }

  onWindowResize(event) {
    this.width = event.target.innerWidth;
    this.height = event.target.innerHeight;
    this.shouldAlert();
  }

  shouldAlert() {
    if (this.width < this.goodWidth) {
      window.alert(
        'warning message to the user if user is trying to view the application with less than 1600 width'
      );
    }
  }
}

Working example: https://stackblitz.com/edit/angular-window-width-1qbtpx?file=src/app/app.component.ts

  • Related