How can I change the css style in another component by clicking the button?

左心房为你撑大大i 提交于 2021-01-28 19:42:35

问题


I have developed a component test1 which contains a button and a <p>Hello World</p>. When I click on the button the background color of the paragraph changes. But now I want to change the background color in app.component when I click on the button. I tried to solve the problem with @Input, but unfortunately it does not work yet. Can you please help me? My Stackblitz

My code:

// test1.component

// HTML
<button type="button" (click)="testHandler()">Change Color</button>
<p [class.toggled]="classToggled">Hello World</p>

// CSS
.toggled {
background-color: blue !important;
}

// TS
public classToggled = false;
testHandler() {
this.classToggled = true;
}
// app.component

// HTML
<div class="wrapper" [class.test1]="classToggled">
  <router-outlet></router-outlet>
</div>

// CSS
.test1 {
  background-color: red !important;
}

// TS
 @Input()  public classToggled = false;

回答1:


There are multiple ways to do it.

For unrelated components, you could use a singleton service to share a styling object between the components and bind it using [ngStyle].

styling.service.ts

@Injectable({ providedIn: 'root' })
export class StylingService {
  sharedStyleSource = new ReplaySubject<any>(1);
  public sharedStyle$ = this.sharedStyleSource.asObservable();

  constructor() { }

  newStyle(value: any) {
    this.sharedStyleSource.next(value);
  }
}

app.component.ts

import { StylingService } from './styling.service';

@Component({
  ...
})
export class AppComponent  {
  constructor(private styling: StylingService) { }

  onClick() {
    this.styling.newStyle({ 'background-color': 'blue' });
  }
}

app.component.html

<button (mouseup)="onClick()">Change child style</button>

<app-test></app-test>

test.component.ts

import { StylingService } from '../styling.service';

@Component({
  ...
})
export class TestComponent {
  constructor(private styling: StylingService) { }
}

test.component.html

<p [ngStyle]="(styling.sharedStyle$ | async)">
  test works!
</p>

Working example: Stackblitz




回答2:


Hello you can use ngClass and pass a parameter. NgClass Angular



来源:https://stackoverflow.com/questions/63976936/how-can-i-change-the-css-style-in-another-component-by-clicking-the-button

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