简体   繁体   English

在 Angular 中保持 scope 中的变量 9

[英]Keeping variable in scope in Angular 9

I come from AngularJS, I have just recently jumped to Angular 9.我来自AngularJS,最近刚跳到Angular 9。

I have a toggle state (dark mode on or off) that I want to maintain and make available to all components.我有一个切换 state(暗模式打开或关闭),我想维护它并使其可用于所有组件。

I toggle it in the root route, and it should keep the state for all the session and for all views and routes.我在根路由中切换它,它应该为所有 session 以及所有视图和路由保留 state。

<button (click)="darkmode()">Dark mode</button>

export class ExhibitorMainViewComponent implements OnInit {

  exhibitors = exhibitors;

  public dark:boolean = false;
  public body = document.getElementsByTagName('body')[0];

  constructor(

  ) { }


  darkmode = function() {
    this.dark = !this.dark;
    this.dark ? this.body.classList.add('dark') : this.body.classList.remove('dark');
  } 
}

This will activate it for the component used in the root route, but it disappears once i go to a child component (other route) and when I come back also.这将为根路由中使用的组件激活它,但是一旦我 go 到子组件(其他路由)并且当我回来时它也会消失。

I'm used to setting a $scope variable that will be available on all the app as long as I use the same controller.我习惯于设置一个 $scope 变量,只要我使用相同的 controller,它就可以在所有应用程序上使用。

How does one manage this in Angular?如何在 Angular 中管理这个?

There are several things here.这里有几件事。

First, if you want to keep a variable available globally you should use a service with providedIn: 'root':首先,如果你想保持一个全局可用的变量,你应该使用一个提供providedIn的服务:'root':

@Injectable({
    providedIn: 'root'
})
export class DarkModeService {

    private darkmode = false;

    toggle() {
        this.darkmode = !this.darkmode;
    }

    get() {
        return this.darkmode;
    }

}

Then inject your service to get the darkmode value in any service / component.然后注入您的服务以获取任何服务/组件中的暗模式值。

But here your problem seems to be that your DOM manipulation (set a 'dark' class to the body tag) do not remains when you change routes.但是在这里,您的问题似乎是当您更改路线时,您的 DOM 操作(将“暗” class 设置为主体标签)不会保留。 This may be because the app is reloading, how do you change route?这可能是因为应用程序正在重新加载,您如何更改路线? You should use link with a routerLink attribute, this way DOM changes are done inside the and your tag won't change (and keep your class).您应该使用带有 routerLink 属性的链接,这样 DOM 更改是在内部完成的,并且您的标签不会更改(并保留您的类)。

 <a routerLink="/heroes" routerLinkActive="active">Heroes</a>

Also the preferred way to manipulate the DOM with angular is to use Renderer2:此外,使用 angular 操作 DOM 的首选方法是使用 Renderer2:

@Component({
  template: `<button (click)="toggleDarkmode()">Dark mode</button>`
})
export class MyComponentThatNeedsDarkModeValue {

    constructor(private renderer: Renderer2) {}

    toggleDarmode() {
        this.renderer.addClass(document.body, 'dark');
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM