Home > Enterprise >  Angular - Change the container height based on the route
Angular - Change the container height based on the route

Time:11-26

I have a container where I load my grids based on the route. For example,

admin.component.html

    <div class="admin-right-panel">              
      <div class="grid-style">
         <router-outlet></router-outlet>
      </div>
    </div>

In the router-outlet, I will load my grid pages/components based on the route Here is the CSS for above HTML

admin.component.scss

    .admin-right-panel {
        height: 60vh;
    }

So, there is an ask for me, where I need to increase this height when I load a specific page into the container.

Let's say I have components A, B, C and when I load B then I need the height to be 80vh, but keep as 60vh in the case of A, B.

Each component has it's own HTML, SCSS, TS files. Is there a way I can implement this logic? Please suggest.

CodePudding user response:

You can conditionally add class using ngClass and subscribing to Router events to check what is the path of the URL.

import {Router, NavigationEnd, ActivatedRoute} from '@angular/core';

...
path!: string;

constructor(private router: Router, private route: ActivatedRoute) {
   this.router.events.pipe(filter((event) => event instanceOf NavigationEnd).subscribe((data) => { 
       this.path = this.route.snapshot.path;
   })
}

Using path, set the component's class.

<div [ngClass]="{ 'extraHeight': path === '<YourPath>' }"> ... </div>

CodePudding user response:

Pre-requisite: Create a new class in stylesheet with the required view height in your edge case. Then, you should be able to do any of the following:

  1. You can use ngClass directive to toggle a class name via a typescript variable.
  2. You can also use [class.largeView]="condition_in_typescript" to add a class largeView to your list of classes. It will only get added when condition is true.
  3. You can wrap two layouts in ngTemplate with a *ngIf and toggle according to path variable in typescript.
  4. You can use HostBinding in a directive to bind multiple classes in your element.
  • Related