change app.components style from different component in angular 2

混江龙づ霸主 提交于 2019-12-13 02:54:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!