Angular2 how to call function on click event from

2019-09-14 18:51发布

问题:

I have two components : Menu1and2 and Menu3

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>

It has a click event that calls a function in Menu3.component.ts that retrieve datas that should be display in Menu3.component.html

How to make the function of Menu3 executed only when the Menu1and2's click event is clicked ?

回答1:

Er.I think you're going wrong solution.

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])
            }
        });
    }
 }

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 to use

1.declare as 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 it anywhere where you can get the instance of eventService.

WARNING. Remember!!! Keep the instance of eventService is a singleton in Your App