实现思路
- 属性绑定实现全局配置参数影响子组件样式:
- 在父组件中定义一个全局配置对象,包含影响子组件显示样式的参数。
- 通过
@Input()
装饰器将配置对象传递给子组件,子组件根据接收到的配置参数动态设置自身的样式。
- 事件绑定实现子组件按钮点击更新全局状态变量:
- 在父组件中定义一个全局状态变量。
- 子组件通过
@Output()
装饰器和 EventEmitter
来发射事件,当特定按钮被点击时,向父组件发射事件。
- 父组件监听子组件发射的事件,接收到事件后更新全局状态变量,然后通过属性绑定将更新后的状态变量传递给所有相关子组件,子组件根据新的状态变量更新自身显示。
关键代码片段
- 父组件(
app.component.ts
):
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
globalConfig = {
styleParam: 'default - style'
};
globalStatus = 0;
handleChildClick() {
this.globalStatus++;
}
}
<!-- app.component.html -->
<app - child - component
[config]="globalConfig"
(childClick)="handleChildClick()"></app - child - component>
<app - another - child - component
[config]="globalConfig"
(childClick)="handleChildClick()"></app - another - child - component>
- 子组件(
child - component.ts
):
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app - child - component',
templateUrl: './child - component.html',
styleUrls: ['./child - component.css']
})
export class ChildComponent {
@Input() config: any;
@Output() childClick = new EventEmitter<void>();
onButtonClick() {
this.childClick.emit();
}
}
<!-- child - component.html -->
<button (click)="onButtonClick()">Click me</button>
<div [ngStyle]="{ 'background - color': config.styleParam }">
This is a child component
</div>
- 另一个子组件(
another - child - component.ts
类似):
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app - another - child - component',
templateUrl: './another - child - component.html',
styleUrls: ['./another - child - component.css']
})
export class AnotherChildComponent {
@Input() config: any;
@Output() childClick = new EventEmitter<void>();
onButtonClick() {
this.childClick.emit();
}
}
<!-- another - child - component.html -->
<button (click)="onButtonClick()">Click me</button>
<div [ngStyle]="{ 'color': config.styleParam }">
This is another child component
</div>