user8827176
user8827176

Reputation:

Where can I check the window width (for mobile header) in Angular?

I want to display two different headers (one for PC and one for mobile) in an Angular SPA depending on the screen size.

My first question is: should I put the mobile header in a seperate component or as different CSS using the @media tag?

My second question is: where should I check the screenwidth and tell Angular to load a different component or different CSS depending on the screen width? I.e. in the app.component.html (using ng-if), in the app.component.ts, in the css...

Thanks in advance!

Upvotes: 0

Views: 1074

Answers (1)

joshrathke
joshrathke

Reputation: 7774

If you are purely interested in altering the view using CSS on a small scale I would just use Media Queries.

@media (max-width: 640px) {
    .element {
        display: none
    }
}

If you are doing this on a large scale you might want to look into some responsive frameworks, specifically Angular Material

Otherwise, if you want to load different components into the view depending on screensize, you would need to move beyond CSS and put the logic that checks screen size, into a Service that Angular can watch and react to as necessary.

screen-size.service.ts

// Initialize the Screen Size Behavior Subject
private ScreenSize$: BehaviorSubject<number> = new BehaviorSubject<number>(window.innerWidth);
// Convert the Screen Size Behavior Subject into an Observable
ScreenSize: Observable<number> = this.ScreenSize$.asObservable();

constructor() {
    // Initialize the Event Listener for the Resizing of the Window
    window.addEventListener('resize', () => {
        // Update the Screen Size Behavior Subject
        this.updateScreenSize(window.innerWidth);
    })
    // Classify Screen Size
    this.classifyScreenSize();
}

// Update the Screen Size Behavior Subject
private updateScreenSize(ScreenSize: number): void {
    this.ScreenSize$.next(ScreenSize);
}

By using the above code in a service you can subscribe to the ScreenSize Observable throughout your app and your components can respond accordingly.

Upvotes: 1

Related Questions