简体   繁体   中英

Communicating events between two sibling components in angular

In my parent html template, I have:

<floor (floorCodeChanged)="setSelectedFloorCode($event)"></floor>
 <room></room>

In my parent.ts file, I have a function that sets the floorCode:

setSelectedFloorCode(floorCode: string) {
    this.floor = floorCode;
 } 

My floor html template is:

<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:

@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:

<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 .

@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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM