[英]Communicating events between two sibling components in angular
In my parent html template, I have: 在我的父html模板中,我有:
<floor (floorCodeChanged)="setSelectedFloorCode($event)"></floor>
<room></room>
In my parent.ts file, I have a function that sets the floorCode: 在我的parent.ts文件中,我有一个设置floorCode的函数:
setSelectedFloorCode(floorCode: string) {
this.floor = floorCode;
}
My floor html template is: 我的地板html模板是:
<mat-form-field>
<mat-select (selectionChange)="emitChangedFloorCode($event)">
<mat-option> 1 </mat-option>
<mat-option> 2 </mat-option>
...
</mat-select>
</mat-form-field>
In my floor.ts file, I have: 在我的floor.ts文件中,我有:
@Output() floorCodeChanged = new EventEmitter<string>();
... ...
emitChangedFloorCode($event: MatSelectChange) {
this.floorCodeChanged.emit($event.value);
}
As soon as the floorCodeChanged has emitted the event, I want my room component to call a function inside room.ts file to do something with the change like: floorCodeChanged发出事件后,我希望我的房间组件调用room.ts文件中的一个函数来对更改执行以下操作:
<floor (floorCodeChanged)="setSelectedFloorCode($event)"></floor>
<room (onFloorCodeChange)="doSomething($event)></room>
How can I achieve this? 我该如何实现?
You can do that with a shared service containing a Subject . 您可以使用包含Subject的共享服务来做到这一点。
@Injectable()
export class SharedService {
event$ = new Subject<string>();
}
After you have provided the service in the components parent module, you can inject the shared service with 在组件父模块中提供服务后,可以使用以下命令注入共享服务:
constructor(private sharedService: SharedService) {}
and dispatch events between components by 并在组件之间调度事件
emitChangedFloorCode($event: MatSelectChange) {
this.sharedService.event$.next($event.value);
}
and you can listen to these events by subscribing to the subject 您可以通过订阅主题来收听这些事件
this.sharedService.event$.subscribe(data => console.log(data));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.