您也可以选择使用 BehaviorSubject
替代 EventEmitter
。这样做的好处在于可以设置初始值。请看以下示例:
StackBlitz 示例
主应用组件(App Component)
@Component({
selector: 'app-root',
imports: [AppChild, AppChildTwo, AsyncPipe],
standalone: true,
templateUrl: './app.component.html',
})
export class App implements OnInit, AfterViewInit {
// 将 EventEmitter 替换为 BehaviorSubject,并设置初始值
onGreetingChange = new BehaviorSubject<string>('Hola!!');
greetingTwo!: string;
// 构造函数、ngOnInit 和 ngAfterViewInit 中不再需要 emit 事件
}
HTML 模板
<div><app-greeting [greeting]="onGreetingChange | async"></app-greeting></div>
<div>
<app-greeting-two (greetingTwo)="greetingTwo = $event"></app-greeting-two>
</div>
<h2>{{ greetingTwo }}</h2>
子组件一(AppChild)
@Component({
selector: 'app-greeting',
standalone: true,
template: '<h1>{{ greeting }} Everyone!</h1>',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class AppChild {
@Input() greeting!: string | null;
}
子组件二(AppChildTwo)
@Component({
selector: 'app-greeting-two',
standalone: true,
template: '<h1>AppChildTwo: {{ greetingTwo | async }} Everyone!</h1>',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
imports: [AsyncPipe],
})
export class AppChildTwo {
// 这里同样使用 BehaviorSubject 并设置初始值
@Output() greetingTwo = new BehaviorSubject('Initial greeting TWO');
}