问题描述
我有两个组件:Menu1and2和Menu3
I have two components : Menu1and2 and Menu3
这是我的Menu1and2.component.html
Here's my 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
It has a click event that calls a function in Menu3.component.ts that retrieve datas that should be display in Menu3.component.html
如何仅在单击Menu1and2的click事件时执行Menu3的功能?
How to make the function of Menu3 executed only when the Menu1and2's click event is clicked ?
推荐答案
Er。我认为您要使用错误的解决方案。
Er.I think you're going wrong solution.
我有一个使用事件分发的解决方案,其他linster处理事件。在Angular2(2.4.10)中,对我来说效果很好。
I have a solution that use Event dispatch,and other linster to handler the event.And it works well for me in 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
Code: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。在@NgModule中声明为提供程序
1.declare as provider in @NgModule
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
...
EventService
...
],
bootstrap: []
})
2。添加事件处理程序
2.Add Event Handler
this.eventService.on("gologin", (item) => {
console.log(item);
});
3。调度事件
this.eventService.trigger("gologin", {})
4因此,U可以在可以获取eventService实例的任何地方使用它。
4.So , U can use it anywhere where you can get the instance of eventService.
警告。记得!!!在您的应用中将eventService的实例保持为单例
这篇关于Angular2如何在另一个组件的click事件上调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!