Hide and Show angular 4 component depending on route

后端 未结 5 1735
渐次进展
渐次进展 2021-02-01 19:03

Hi there Im not sure if this is possible... basically I want to be able to show a component but only if the route matches and hide a component if the route matches Ive tried thi

5条回答
  •  独厮守ぢ
    2021-02-01 19:03

    This is in reference to the comment posted by SUNIL JADHAV. Instead of exposing the router handle on the templates we can define it inside a function and call it in the template.

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'my-component',
      templateUrl: './my.component.html',
      styleUrls: ['./my.component.scss']
    })
    export class MyComponent implements OnInit {
    
      constructor(
        private router: Router,
      ) {}
    
      ngOnInit() {
      }
    
    
      /**
       * Check if the router url contains the specified route
       *
       * @param {string} route
       * @returns
       * @memberof MyComponent
       */
      hasRoute(route: string) {
        return this.router.url.includes(route);
      }
    }
    
    

    Then in the html file we can use it like so

    
    
    First View
    Second View

提交回复
热议问题