我在主admin-tournament组件
中有这个结构管理-tournament.component.html:
<fixture-league></fixture-league>
夹具-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>
我想处理在AdminTournamentComponent内部而不是FixtureLeagueComponent上的MatchComponent上发出的点击事件(因为我想改变其他人的行为“TournamentComponents”但保留FixtureComponent结构)。
是否可以选择将未处理的事件提升为“灯具联盟”的父母,如:
<fixture-league (onDateClick)="doSomething()"></fixture-league>
如果没有,我如何避免在FixtureComponent上创建相同的事件emmiters但在AdminTournamentComponent上处理这些事件?
答案 0 :(得分:1)
在处理多个组件级别时,通常更容易将事件处理移动到专用服务。然后,每个组件都可以注入此服务,并订阅该事件或向其发出一些值。
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);
}
}
然后注入这样的服务并使用它:
constructor(public eventService: MyEventService) {}
// emitting
<team [team]="match.local_team" (click)="evetService.emit('localClick')"></team>
// subscribing
ngOnInit() {
this.eventService.subscribe(type => { console.log(type); });
}