Angular View 绑定未使用简单布尔值更新

Rob*_*ter 5 html binding view typescript angular

再见,这可能是一个菜鸟问题,但我无法让它发挥作用。

我有一个简单的服务,可以切换布尔值,如果布尔值为 true,则活动类应该出现在我的 div 上,如果为 false,则没有类......就这么简单。但是布尔值已更新,但我的视图没有对此做出反应。我是否必须以某种方式通知我的视图某些内容发生了变化?

服务:

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

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

    public menuActive = false;

    toggleMenu() {
      this.menuActive = !this.menuActive;
    }
}
Run Code Online (Sandbox Code Playgroud)

查看(左侧菜单组件):

 <div id="mainContainerRightTop" [class.active]="classToggleService.menuActive == true">
Run Code Online (Sandbox Code Playgroud)

切换点(顶部菜单组件):

<a id="hamburgerIcon" (click)="classToggleService.toggleMenu()">
Run Code Online (Sandbox Code Playgroud)

PSi*_*ngh 3

这是因为您正在更改服务上的值而不是组件上的值,因此 Angular 不需要更新组件,因为它没有更改。如果您想在修改服务元素时更新组件的视图,则必须使用可观察对象和主题,并订阅它们。这样当元素发生变化时,它会自动通知所有订阅的组件。

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

    public menuSubject: Subject<boolean> = new BehaviorSubject<boolean>(false);
    public menuActive = this.menuSubject.asObservable();
    toggleMenu(val : boolean) {
      this.menuSubject.next(val);
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的组件中,只需实现 OnInit 接口并订阅服务中的可观察对象:

public localBool = false;
ngOnInit() {
   this._myService.menuActive.subscribe(value => this.localBool = value);
}
ComponentToggleMenu() {
   this._myService.toggleMenu(!this.localBool);
}
Run Code Online (Sandbox Code Playgroud)

然后你的html:

    <div id="mainContainerRightTop" [class.active]="localBool">
   <a id="hamburgerIcon" (click)="ComponentToggleMenu()">
Run Code Online (Sandbox Code Playgroud)