angular - 导航显示/隐藏不起作用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;
}
}
解决方案
从导航组件中删除提供者应该可以工作
@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
推荐阅读
- javascript - 防止提交功能的多个Javascript执行
- javascript - 在构造函数中的事件侦听器完成更改后,组件不会重新渲染
- python - 如何在经过训练的模型上使用新数据集?
- r - 按组重置数字索引列
- flutter - 如何在容器内的文本左侧添加图标
- sql - 设计一个数据库来容纳一维数据
- azure-devops - 如何找出 Azure DevOps Services 管道需求/能力要求以选择某些特定代理?(隐式和显式要求)
- python - 忽略命令无异常:discord.ext.commands.errors.CommandNotFound:找不到命令“send_dm”
- c++11 - 二分法如何找到x1和x2?
- javascript - 有没有办法导入文本文件并将其显示到网页上,但也可以对文本文件的每一行进行特定更改?