Reputation: 35
I have this structure inside of a main admin-tournament component
admin-tournament.component.html:
<fixture-league></fixture-league>
fixture-league.component.html
<md-tab-group>
<md-tab *ngFor="let f of fixture" label="{{ f.date | date }}">
<match *ngFor="let m of f" [match]="m"></match>
</md-tab>
</md-tab-group>
match.component.html
<team [team]="match.local_team" (click)="onLocalClick.emit()"></team>
<ul>
<li (click)="onDateClick.emit()">{{ match.date | date:"HH:mm"}}</li>
<li (click)="onResultClick.emit()">{{ match.result | myResultPipe }}</li>
<ul>
<team [team]="match.visitor_team" (click)="onVisitorClick.emit()"></team>
I want to handle the click events that are emited on MatchComponent inside of AdminTournamentComponent and not on FixtureLeagueComponent (because I want to change the behavior on others "TournamentComponents" but keep the FixtureComponent structure).
Is there any option to raise the unhandled events to "fixture-league" parent like:
<fixture-league (onDateClick)="doSomething()"></fixture-league>
If not, how can I avoid to create the same event emmiters on FixtureComponent but handle those events on AdminTournamentComponent?
Upvotes: 1
Views: 289
Reputation: 18429
When dealing with multiple component levels, it is usually easier to move the event handling to dedicated service. Every component can then inject this service and either subscribe to the event or emit some value to it.
import { EventEmitter, Injectable } from '@angular/core';
@Injectable()
export class MyEventService {
private emitter = new EventEmitter<any>();
public subscribe(callback: Function): void {
this.emitter.subscribe(callback);
}
public emit(value: any = {}): void {
this.emitter.emit(value);
}
}
Then inject such a service and use it:
constructor(public eventService: MyEventService) {}
// emitting
<team [team]="match.local_team" (click)="evetService.emit('localClick')"></team>
// subscribing
ngOnInit() {
this.eventService.subscribe(type => { console.log(type); });
}
Upvotes: 1