如何使用EventEmitter将功能传递给子组件?

时间:2018-10-31 09:15:18

标签: angular nativescript

我有一个父子组件设置,其中子元素中的(tap)事件发生,我需要调用父方法。我正在尝试eventEmmiter,但收到此错误:

  

错误:com.tns.NativeScriptException:无法找到模块:“事件”,   相对于:app / tns_modules /

代码段

Parent.component.html

<app-header (thisEvent)="navigate($event)"></app-header>

Parent.component.ts

import { Component } from "@angular/core";
@Component({
  moduleId: module.id,
  selector: "app-main",
  templateUrl: "./parent.component.html",
  styleUrls: ["./parent.component.css"]
})
export class ParentComponent {
naviagte(args){
this.router.navigate(["/"]);
}
}

Child.component.html:

<Button text="Tap" class="btn btn-primary" (tap)="onTap($event)"></label>

Child.component.ts:

import { Component, Input, Output } from "@angular/core";
import { EventEmitter } from "events";
@Component({
  selector: "app-header",
  moduleId: module.id,
  templateUrl: "./child.component.html",
  styleUrls: ["./child.component.css"]
})
export class ChildComponent {
  @Output()
  thisEvent= new EventEmitter();
  navigate(args) {
    this.thisEvent.emit(null);
  }
}

3 个答案:

答案 0 :(得分:4)

应从EventEmitter而非@angular/core导入events

import { Component, Input, Output, EventEmitter } from "@angular/core";

答案 1 :(得分:0)

您收到的错误是由于导入错误

import { EventEmitter } from "events";

EventEmitter应该从角度/核心包中导入

import { EventEmitter } from '@angular/core';

答案 2 :(得分:0)

从“ @ angular / core”导入{EventEmitter};

来自“ @ angular / core”的EventEmitter