angular - Angular2 how to call function on click event from another component -
i have 2 components : menu1and2 , menu3
here's 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>
it has click event calls function in menu3.component.ts retrieve datas should display in menu3.component.html
how make function of menu3 executed when menu1and2's click event clicked ?
er.i think you're going wrong solution.
i have solution use event dispatch,and other linster handler event.and works 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} "@angular/core"; import {definedevent} "../domain/definedevent"; import {loggerservice} "./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 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]) } }); } }
code: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(); } }
and how use
1.declare provider in @ngmodule
@ngmodule({ declarations: [ ... ], imports: [ ... ], providers: [ ... eventservice ... ], bootstrap: [] })
2.add event handler
this.eventservice.on("gologin", (item) => { console.log(item); });
3.dispatch event
this.eventservice.trigger("gologin", {})
4.so , u can use anywhere can instance of eventservice.
warning. remember!!! keep instance of eventservice singleton in app
Comments
Post a Comment