首页 > 解决方案 > 导航显示/隐藏不起作用Angular 6

问题描述

我只是尝试隐藏登录组件上的菜单,可见属性是使用服务的构造函数设置的,但之后就不起作用了。

使用构造函数设置的值工作正常,但调用hide()函数在调试中工作正常,但设置隐藏/可见导航栏。

导航服务.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class NavigationService {
  visible: boolean;

  constructor() { 
    this.visible = true; //It's working either set true or fasle 
  }

  hide() { 
    this.visible = false; //Function working fine but Not reflecting in UI
  }

}

导航.component.html

<!--Main Navigation-->
<header *ngIf="nav.visible">
</header>

登录组件.ts

    import { Component, OnInit} from '@angular/core';
    import { NavigationService } from '../../navigation.service';
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.scss'],
    })
    export class LoginComponent implements OnInit {
      constructor(public nav: NavigationService) {
            this.nav.hide();
     }
      ngOnInit() {

      }
    }

导航.component.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { NavigationService } from '../../navigation.service';
@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.scss'],
  providers: [NavigationService]
})
export class NavigationComponent implements OnInit {
  @ViewChild('sidenav') sidenav: ElementRef;
  clicked: boolean;
  constructor(public nav: NavigationService) {
    this.clicked = this.clicked === undefined ? false : true;
  }

  ngOnInit() {
  }

  setClicked(val: boolean): void {
    this.clicked = val;
  }
}

标签: angularangular-services

解决方案


从导航组件中删除提供者应该可以工作

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.scss']
})
export class NavigationComponent implements OnInit {
  @ViewChild('sidenav') sidenav: ElementRef;
  clicked: boolean;
  constructor(public nav: NavigationService) {
    this.clicked = this.clicked === undefined ? false : true;
  }

  ngOnInit() {
  }

  setClicked(val: boolean): void {
    this.clicked = val;
  }
}

请检查 stackblitz https://stackblitz.com/edit/angular-o9jya9?file=src%2Fapp%2Fnavigation.service.ts


推荐阅读