[Fixed] Method is not called when button is clicked

Issue

In the below code I am learning the event emitters and output decorators.

The problem I am facing now is, when I click the button as shown below:

<button (click)="emitValueToParentComponent">CLICK to emit value</button>

the method emitValueToParentComponent never gets called and the console.log does not print anything on the browser’s console.

Please let me know how to call the method emitValueToParentComponent on button click

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

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

      @Input() myInputText : string;
      @Output() mOutputEvtEmitterFromStudentToParentComponent: EventEmitter<string> = new EventEmitter();
      valueToEmit: string = "emitted value from child student component to parent component";
      
      constructor() {
       }
     
      ngOnInit(): void {
        console.log("ngOnInit myInputText: " + this.myInputText);
      }

      emitValueToParentComponent() {
        this.mOutputEvtEmitterFromStudentToParentComponent.emit(this.valueToEmit);
        console.log("emitValueToParentComponent valueToEmit: " + this.valueToEmit);
        console.log("emitted value");
      }
    }
<div>
    <button (click)="emitValueToParentComponent">CLICK to emit value</button>
    
</div>

Solution

<div>
<button (click)="emitValueToParentComponent()">CLICK to emit value</button>

</div>

You need to actually call the function emitValueToParentComponent() on click.Passing reference like that is a part of react ecosytem.

Leave a Reply

(*) Required, Your email will not be published