Custom template with functionality inside Layout component provided by the current route

Viewed 39

I have an Angular layout and it is used by multiple routes. I wanted to know if it is possible to have an area inside it that would be controller by the current route. For example some buttons with specific logic for on click.

Layout:

<div fxLayout="row" fxLayoutAlign="space-between center">
  <div>
    <span class="titleBig">Title</span>
  </div>
  <div>
    /* Here should be the custom template from the current route */
  </div>  
</div>  
<router-outlet></router-outlet>

Route 1:

<button type='button' mat-button (click)="doMath()">Do Math</button>

Route 2:

<button type='button' mat-button (click)="doPlayOutside()">Do Play</button>
1 Answers

you have two options, add a single button, then modify the button so that it executes based on the route.

html

<button type='button' mat-button (click)="multiPurproseButton()">Do Math</button>

ts

multiPurproseButton() {
  // write some logic to get the path from the url, I am keeping it simple!
  const path = this.router.url.split('/').pop();
  switch(path) {
    case 'home':
       this.doMath();
    case 'about':
       this.doPlayOutside();
  }
}

The second option is to use ngSwitch this will render multiple html based on the route you are on.

html

<div [ngSwitch]="currentPath">
  <div *ngSwitchCase="'home'">
    <h2>Map View Content</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Est minima ipsa ex modi laudantium aliquam dolor expedita, numquam officiis omnis.</p>
  </div>
  <div *ngSwitchCase="'about'">
    <h2>List View Content</h2>
    <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Praesentium officiis totam debitis? Repellat non a magni mollitia provident, quaerat eum.</p>
  </div>
  <div *ngSwitchDefault>OtherWise</div>
</div>
</div>

ts

get currentPath() {
  // write some logic to get the path from the url, I am keeping it simple!
  const path = this.router.url.split('/').pop(); 
  return path;
}
Related