Mehul
Mehul

Reputation: 45

Angual 6 event emitter - does not work

Can anyone please spot what is wrong in this code, I am not getting event back to appcomponent

test1.component.html

<input type="text" [(ngModel)]="mytext1" >
<button 
  id="clicked" 
  name="Click Me" 
  class="button"  
  (click)="returnData();">
  Click Me! 
</button>

test1.component.ts

import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter
} from '@angular/core';
@Component({
  selector: 'app-test1',
  templateUrl: './test1.component.html',
  styleUrls: ['./test1.component.css']
})
export class Test1Component implements OnInit {
  constructor() {}
  @Input() mytext1: string;
  @Output() dataEmit: EventEmitter < string > = new EventEmitter < string > ();;

  ngOnInit() {}

  changeText1($event) {
    this.mytext1 = $event;
  }

  returnData() {
    console.log("button clicked");
    this.dataEmit.emit(this.mytext1);
  }

}

app.component.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>
  {{testText2}}
</div>

app.component.ts

import {
  Component,
  Input,
  OnInit
} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'AngularDemo';
  public testText2: string = "from parent";
  childmessage: string = "I am passed from Parent to child component";

  getToggle($event) {
    this.testText2 = $event;
  }

  ngOnInit() {

  }
}

I am not getting a response on app.component.ts, neither getting a debugger.

Upvotes: 1

Views: 464

Answers (3)

Vinod Bhavnani
Vinod Bhavnani

Reputation: 2225

The problem is here:

<app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>

(returnData) should be (dataEmit)

dataEmit is the actual event (of type eventemitter) returnData is just a method called on click of the button :)

Also getTest1Data($event) should be getToggle($event)

Hope this helps.

Upvotes: 1

Alexandre Annic
Alexandre Annic

Reputation: 10778

Your output name is dataEmit. So refacto your component call from this

   <app-test1 [mytext1]="childmessage" (returnData)="getTest1Data($event)"></app-test1>

to this:

   <app-test1 [mytext1]="childmessage" (dataEmit)="getTest1Data($event)"></app-test1>

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68685

You have wrong binding to the event emitter. You need to bind to the Output parameter, not to the function which emits (dataEmit instead of returnData) event and replace getTest1Data with getToggle

<app-test1 [mytext1]="childmessage" (dataEmit)="getToggle($event)"></app-test1>

Upvotes: 1

Related Questions