【问题标题】:How to communicate from Child to Parent page using EventEmitters如何使用 EventEmitters 从子页面到父页面进行通信
【发布时间】:2018-12-14 22:18:06
【问题描述】:

我是 Angular 的新手,我现在正在使用 Angular 开发离子应用程序,我的要求是使用事件发射器从子页面到父页面进行通信(只想从子页面更改父页面标题,我的代码如下,请建议我如何我这样做),我什至不知道这个概念有人可以帮助我吗

parent.html:-

<ion-header>

  <ion-navbar>
    <button menuToggle left>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>{{title}}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
</ion-content>

parnet.ts:

export class Parent{
  title:string;
  getNotification(evt) {
    this.title = ""+evt;
   }
}

child.html:

<ion-content padding>
    <h2>Grocery Page</h2>
    <button ion-button (click)="sendNotification()" color="secondary" full>Notify my parent!</button>
</ion-content>

child.ts:

export class Child{

  @Output() notifyParent: EventEmitter<any> = new EventEmitter();
  sendNotification() {
    this.notifyParent.emit('Parent Page');
   }
}

【问题讨论】:

  • 子元素名称是什么
  • 我更新了我的代码,请立即查看
  • 仍然没有发布子组件选择器
  • 我更新了,请立即查看

标签: angular ionic-framework


【解决方案1】:

您的子组件的实现是正确的,现在您只需要在父组件中侦听notifyParent 事件并将值更改为接收一个,如下所示:

<child-component (notifyParent)="getNotification($event)"></child-component>

这是一个简单的DEMO

【讨论】:

    【解决方案2】:

    在您的父组件的模板上,您可以为您的子组件设置一个事件发射器,如下所示,

    <child (notifyParent) = "getNotification($event)"></child>
    

    子组件:

    export class Child{
    
       @Output() notifyParent: EventEmitter<string> = new EventEmitter();
    
       sendNotification() {
         this.notifyParent.emit('Parent Page');
       }
    }
    

    父组件:

    export class Parent{
      title:string;
      getNotification(evt) {
         this.title = evt;
      }
    }
    

    【讨论】:

    • 如果我喜欢这个子页面 UI 出现在我的父页面 UI 中
    • 我只想从子页面更改父页面操作栏标题
    • 子组件的整个概念就是这样。在父组件 UI 中。如果您只是想从其他使用服务的地方更改标题。
    • 哦,不可能使用 EventEmiters 吗?
    • 您的子页面在哪里,不是在您的父页面中吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    相关资源
    最近更新 更多