Auto close in Angular Sidebar component
27 Apr 20244 minutes to read
The Sidebar often behaves differently on mobile display and differently on desktop display.
It has an effective feature that offers to set it in opened or closed state depending on the specified screen resolution.
This functionality can be achieved through mediaQuery
property that allows you to set the Sidebar in an expanded state or collapsed state only in user-defined resolution.
window.matchMedia() method returns the object of parsed
media query
string.
The value of matchMedia() can be any of the media features of CSS @media rule. For example, min-width and max-width.
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { SidebarModule } from '@syncfusion/ej2-angular-navigations'
import { Component } from '@angular/core';
@Component({
imports: [
SidebarModule
],
standalone: true,
selector: 'app-root',
styleUrls: ['./app.component.css'],
template: ` <ejs-sidebar id="default-sidebar" #sidebar [width]="width" [mediaQuery]= "mediaQuery" [closeOnDocumentClick]='colseOnDocumentClick'>
<div class="title"> Sidebar content</div>
</ejs-sidebar>
<div>
<div class="title">Main content</div>
<div class="sub-title">
Sidebar will collapse and expand in based on screen resolution automatically
</div>
</div>`
})
export class AppComponent {
public width: string = '280px';
public mediaQuery: object = window.matchMedia('(min-width: 600px)');
colseOnDocumentClick: any;
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
- In the following sample,the Sidebar will be in expanded state only in resolution below
400px
.
max-width
is one of media feature which represents maximum with of display area such as width of the view port.
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { SidebarModule } from '@syncfusion/ej2-angular-navigations'
import { Component } from '@angular/core';
@Component({
imports: [
SidebarModule
],
standalone: true,
selector: 'app-root',
styleUrls: ['./app.component.css'],
template: ` <ejs-sidebar id="default-sidebar" #sidebar [width]="width" [mediaQuery]= "mediaQuery" [closeOnDocumentClick]='colseOnDocumentClick'>
<div class="title"> Sidebar content</div>
</ejs-sidebar>
<div>
<div class="title">Main content</div>
<div class="sub-title">
Sidebar will collapse and expand in based on screen resolution automatically
</div>
</div>`
})
export class AppComponent {
public width: string = '280px';
public mediaQuery: object = window.matchMedia('(max-width: 400px)');
colseOnDocumentClick: any;
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));