0

With learning purpose I have got an scenario and trying to use a service able to dynamically change the class of a component generated by router-outlet.

Following this I have the service with a BehaviorSubject which value is toggled by a function.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DynamicClassesService {
    private stateRouterOutlet: Subject<string> = new BehaviorSubject<string>('am-topMenu');

    stateRouterOutlet$ = this.stateRouterOutlet.asObservable();

    toggleStateRouterOutlet() {
        let current;
        this.stateRouterOutlet.subscribe(res => { current = res });
        current = (current === 'am-topMenu' ? 'am-leftMenu' : 'am-topMenu');
        this.stateRouterOutlet.next(current);
        console.log('Toggled to: ' + current);
    }

I need help for the next step. I do subscribe from the child component and I get the value in constructor and store in a local (of the component) variable as it follow. (Maybe it is wrong)

Have any sense if I declare it (localStateRouterOutlet) as @Input()?

localStateRouterOutlet: string;

 constructor(private dynamicClasses: DynamicClassesService) {
        dynamicClasses.stateRouterOutlet$.subscribe(res => {
            this.localStateRouterOutlet = res;
            console.log(this.localStateRouterOutlet);
        })
    }

Where is the clue to manage that toggle function from the service have effect in this variable?

If I bind

[ngClass] = "localStateRouterOutlet"

Is it supposed to work for my initial purpose? This is the totally wrong concept?

I do apreciate you help in advance.

Community
  • 1
  • 1
Sam
  • 1,459
  • 1
  • 18
  • 32
  • 1
    you could try `[ngClass]="stateRouterOutlet$ | asnyc"` – Aluan Haddad May 02 '17 at 23:37
  • when toggleStateRouterOutlet is called? – Julia Passynkova May 03 '17 at 00:58
  • 1
    @AluanHaddad I tried binding with async pipe as you said and it didn't work but I want to give another try with time and I will come to say what happens. Thank you very much from now, it was usefull and I feel it should resolve by anyway. – Sam May 03 '17 at 12:37
  • @JuliaPassynkova I am calling togleStateRouterOutlet directly from a button (click) on my root component template. It component loads the service. – Sam May 03 '17 at 12:39

0 Answers0