首页 文章

如何使用EventEmitters从Child与Parent页面进行通信

提问于
浏览
1

我是Angular的新手,我现在正在开发使用angular的离子应用程序,我的要求是使用Event Emitters从子页面进行通信(只是想从子页面更改父页面 Headers ,我的代码如下,请建议我怎样才能做到这一点),我甚至不知道这个概念可以帮助我一些人

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

2 回答

  • 0

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

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

    这是一个简单的DEMO .

  • 0

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

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

    ChildComponent:

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

相关问题