问题
I'm trying to change the app.component.html style from another component. I'm my app.component.html I have a I'm using an object with lots of properties for the style.
When a button is clicked from component2 and toggleLayout() is called, this.Data.xmldata.uiStyle[0]['$']['styleForUI'] = "styleLayout2"; will change the shared variable, but app.component doesn't know when the shared variable is changed.
Is this process too indirect, should I be trying to call a method in app.component.ts from outside?
回答1:
You should avoid directly calling component's methods if you can, to reduce coupling. You can use a shared service based on observables.
service
import {Injectable} from '@angular/core';
import {Observable, Subject} from "rxjs";
@Injectable()
export class MessageService
{
private mySubject: Subject<any> = new Subject<any>();
public readonly stylesChanged$: Observable<any> = this.mySubject.asObservable();
brodcastStylesChanged(styles)
{
this.mySubject.next(styles );
}
}
component2
this.messageService.brodcastStylesChanged(styles);
component1
this.messageService.stylesChanged$.subscribe(styles=> {
this.styles= styles;
});
来源:https://stackoverflow.com/questions/49820822/change-app-components-style-from-different-component-in-angular-2