Search code examples
javascriptangularangular-components

Angular @Output not working


Trying to do child to parent communication with @Output event emitter but is no working here is the child component

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

@Component({
  selector: 'app-emiter',
  templateUrl: './emiter.component.html',
  styleUrls: ['./emiter.component.css']
})
export class EmiterComponent implements OnInit {

@Output() emitor: EventEmitter<any>
  constructor() { this.emitor = new EventEmitter()}

   touchHere(){this.emitor.emit('Should Work');
   console.log('<><><><>',this.emitor) // this comes empty
  }

  ngOnInit() {
  }

}

this is the html template

<p>
<button (click)=" touchHere()" class="btn btn-success btn-block">touch</button>
</p>

The console.log inside the touchHere it shows nothing even if I put this inside the parent component it show nothing as well parent component

 import { Component , OnInit} from '@angular/core';
// service I use for other stuff//
    import { SenderService } from './sender.service';
// I dont know if I have to import this but did it just in case
    import { EmiterComponent } from './emiter/emiter.component'

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
      user: any;
      touchThis(message: string) {
        console.log('Not working: ${message}');
      }
        constructor(private mySessionService: SenderService) { }
    }

and here is the html template

<div>
  <app-emiter>(touchHere)='touchThis($event)'</app-emiter>
</div>

Solution

  • Parent component template:

      <app-emitor (emitor)='touchThis($event)'></app-emiter>
    

    In parent template @Output should be 'called', not the child method.

    Also, see: https://angular.io/guide/component-interaction#parent-listens-for-child-event