我只是尝试隐藏Login Component上的菜单,可见属性是通过服务的构造函数设置的,但此后无法正常工作。
使用构造函数设置的值可以正常工作,但是调用hide()
函数可以在调试时很好地工作,但可以将导航栏设置为隐藏/可见。
navigation.service.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
}
}
navigation.component.html
<!--Main Navigation-->
<header *ngIf="nav.visible">
</header>
login.componet.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() {
}
}
navigation.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;
}
}
答案 0 :(得分:1)
从导航组件中删除提供程序应该可以工作
@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