angular 2 - how to hide nav bar in some components

后端 未结 9 733
半阙折子戏
半阙折子戏 2020-12-04 16:07

I am created nav bar separately in nav.component.html ,how to hide nav bar in some components like login.component.

nav.component.html

9条回答
  •  悲哀的现实
    2020-12-04 16:29

    The linked answer above by JaganY is the best answer if you are hiding a mat-sidenav element. You should never have simple code like this require change detection. Here is an example for other types of elements:

    app.componenent.html

        
    

    app.componenent.ts

      @ViewChild('rNav') rNav!: ElementRef;
    
      constructor(public nav: NavbarService) { }
    
      ngAfterViewInit(): void {
        this.nav.setRight(this.rNav);
      }
    

    navbar.service.ts

    import { Injectable, ElementRef } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class NavbarService {
    
      private right!: ElementRef;
      private visible!: boolean;
    
      hideR() { 
        this.visible = false;
        this.right.nativeElement.style.display = 'none';
      }
    
      showR() { 
        this.visible = true; 
        this.right.nativeElement.style.display = 'block';
      }
    
      toggleR() { this.visible ? this.hideR() : this.showR(); }
    
      setRight(e: ElementRef) {
        this.right = e;
      }
    }
    

    child-components.html

    constructor() {
      this.nav.hideR(); // or this.nav.showR();
    }
    

提交回复
热议问题