我有两个组件:Menu1and2和Menu3
这是我的Menu1and2.component.html
<form id="form1" runat="server" class="mainMenuContainer">
<div class="col-lg-12" id="menuContainer" *ngFor="let menu of usermenus">
<div class="panel panel-default col-lg-6 col-md-6 col-sm-12">
<div class="panel-heading">{{menu.Title}}</div>
<div class="panel-body">
<ul class="sub" style="display: block;" *ngFor="let subMenu of menu.SubMenus">
<li><a href="#" (click)="getSubMenu(subMenu.Title)>{{subMenu.Title}}</a></li>
</ul>
</div>
</div>
</div>
</form>
它有一个click事件,它调用Menu3.component.ts中的一个函数来检索应该在Menu3.component.html中显示的数据
如果仅在单击Menu1and2的点击事件时才执行Menu3的功能?
答案 0 :(得分:0)
呃。我认为你的解决方案是错误的。
我有一个使用Event dispatch和其他linster处理事件的解决方案。它在Angular2(2.4.10)中适用于我
@angular/cli: 1.0.0
node: 7.2.0
os: darwin x64
@angular/common: 2.4.10
@angular/compiler: 2.4.10
@angular/core: 2.4.10
@angular/forms: 2.4.10
@angular/http: 2.4.10
@angular/platform-browser: 2.4.10
@angular/platform-browser-dynamic: 2.4.10
@angular/router: 3.4.10
@angular/cli: 1.0.0
@angular/compiler-cli: 2.4.10
<强>代码:EventService 强>
import {Injectable, EventEmitter} from "@angular/core";
import {DefinedEvent} from "../domain/DefinedEvent";
import {LoggerService} from "./LoggerService";
@Injectable()
export class EventService {
private $event: EventEmitter<DefinedEvent>;
constructor(private loggerService: LoggerService) {
this.$event = new EventEmitter();
}
public trigger(type: string, value: any) {
this.loggerService.debug("event has been triggered with type:" + type);
this.$event.emit(new DefinedEvent(type, value));
}
public on(type: string, callback: Function): void {
this.$event.subscribe((item) => {
if (item.type === type && !!callback) {
callback.apply(null, [item])
}
});
}
}
<强>代码:DefinedEvent 强>
export class DefinedEvent {
readonly type: string;
readonly value: any;
readonly time: Date;
constructor(type: string, value: any) {
this.type = type;
this.value = value;
this.time = new Date();
}
}
以及如何使用
1.declare作为@NgModule的提供者
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
...
EventService
...
],
bootstrap: []
})
2.添加事件处理程序
this.eventService.on("gologin", (item) => {
console.log(item);
});
3.Dispatch Event
this.eventService.trigger("gologin", {})
4.所以,你可以在任何可以获得eventService实例的地方使用它。
警告。记得!!!保持eventService的实例是您的应用程序中的单例