【问题标题】:How can I change the css style in another component by clicking the button?如何通过单击按钮更改另一个组件中的 css 样式?
【发布时间】:2020-09-20 08:19:21
【问题描述】:

我开发了一个组件 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;

【问题讨论】:

  • 你的组件 test1 是在 app 组件里面吗?
  • 是的,没错。
  • 然后你可以使用 Output 来代替 Input 装饰器并发出值。

标签: angular typescript angular-event-emitter


【解决方案1】:

有多种方法可以做到这一点。

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

【讨论】:

  • 我看过你的例子并且有一些问题。是否也可以通过单击 test.component 中的段落和 app.component 中的 div 来实现 test.component 中的按钮并更改颜色?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2016-07-26
    相关资源
    最近更新 更多