我有一个导航栏,用于检查打开/关闭变量是真还是假,我将其称为“navcontrol”。 我的导航栏有一个组件,每个页面都有一个不同的组件。
我的 app.component.html :
<app-navbar></app-navbar>
<router-outlet></router-outlet>
问题是,一个按钮改变了 navcontrol,这个按钮在 "app-navbar" 上。每个页面也需要根据navcontrol的值改变padding,它们移动到底部。
所以我在每个页面上都有一个监听器 [class.opened]="navcontrol === true"
,添加一个打开的类,用 css 进行填充。
在 Angular 文档上,我看到我可以ng generate service navbarcontrol
然后像这样使用:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class NavbarcontrolService {
static navcontrol: boolean;
constructor()
{
console.log(NavbarcontrolService.navcontrol)
}
}
然后是我的 navbar.component.ts 和 page1.component.ts :
export class NavbarComponent implements OnInit {
navcontrol = NavbarcontrolService.navcontrol;
然后在我的 page1 html:
<div class="content " [class.toggled]="navcontrol=== true">
我的导航栏 html,其中更改导航控件的按钮是:
<button type="button" class="button"
[class.isopen]="navcontrol=== true"
[class.isclosed]="navcontrol=== false"
(click)="navcontrol= !navcontrol">
</button>
当我点击 "app-navbar" 中的按钮时,它改变了本地 navcontrol 变量,来自 "app-page1" 的文本没有收到更改,因此它们引用不同的变量,而不是单个全局变量。 我怎么能声明一个全局 "navcontrol" 如果我在我的 "app-navbar" 上更改它,我的 "app-page1" 也会检查同一个变量并查看它是否已更改?
最佳答案
您可以在组件中使用属性 getter 和 setter 访问全局变量。此技术将确保对 navcontrol
属性的所有调用最终都将引用相同的全局变量。
export class MyComponent {
constructor(private navbarcontrolService: NavbarcontrolService) { }
get navcontrol(): boolean {
return this.navbarcontrolService.navcontrol;
}
set navcontrol(value: boolean) {
this.navbarcontrolService.navcontrol = value;
}
...
}
服务:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class NavbarcontrolService {
navcontrol: boolean;
}
关于javascript - 应用程序范围内可访问和可变的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50295275/