如何通过单击按钮更改另一个组件中的CSS样式?

问题描述

我已经开发了一个组件test1,其中包含一个按钮和一个<p>Hello World</p>。当我单击按钮时,该段落的背景颜色会更改。但是现在我想在单击按钮时更改app.component中的背景颜色。我试图用@Input解决问题,但是不幸的是它还不能正常工作。你能帮我么? My Stackblitz

我的代码

// 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;

解决方法

有多种方法可以实现。

对于不相关的组件,您可以使用单例服务在组件之间共享样式对象,并使用[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>

工作示例:Stackblitz

,

您好,您可以使用ngClass并传递参数。 NgClass Angular