4
votes

Goodday, This is probably a nooby question but I can't get it to work.

I have a simple service which toggles an boolean, if the boolean is true the class active should appear on my div and if false no class.. Simple as that. But the boolean gets updated, but my view doesn't react to it. Do I somehow have to notify my view that something has changed ?

Service:

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

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

    public menuActive = false;

    toggleMenu() {
      this.menuActive = !this.menuActive;
    }
}

View (left menu component):

 <div id="mainContainerRightTop" [class.active]="classToggleService.menuActive == true">

Toggle point (top menu component):

<a id="hamburgerIcon" (click)="classToggleService.toggleMenu()">
2
try simply by "[class.active]="classToggleService.menuActive"Pardeep Jain
I tried this, but this didn't work so as a test i wrote it out fully by using == trueRoboneter

2 Answers

1
votes

This because you are changing a value on a service not on the component, so Angular don't need to update the component, because it did not change. If you want to update the view of your component when a service element is modified, you have to use an Observables and Subjects, and subscribe to them. In this way when the element is changed, it automatically notify all the subscribed components.

@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);
    }
}

And in your component just implement OnInit interface and subcribe to the observable in the your service:

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

Then your html:

    <div id="mainContainerRightTop" [class.active]="localBool">
   <a id="hamburgerIcon" (click)="ComponentToggleMenu()">
0
votes

Why we need service, this should be integrated with component class. As a general rule, you are not supposed to call service method in template file.

export class TestComponent implements OnInit{
   public menuActive = false;

    toggleMenu() {
      this.menuActive = !this.menuActive;
    }
}

Template:

<div id="mainContainerRightTop" [class.active]="menuActive">