Search code examples
angularangular7eventemitter

how to use EventEmitter in angular7


i define my component in one file and i want to send data form parent to child component in parent function is work properly but eventEmitter not emit

this is my component file have two component

import { Component, OnInit, Inject ,EventEmitter,Output} from '@angular/core';
    import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';

export interface DialogData {
    name: string;
}

@Component({
    selector: 'app-new-time-register',
    templateUrl: './new-time-register.component.html',
    styleUrls: ['./new-time-register.component.scss']
})
export class NewTimeRegisterComponent implements OnInit {

    constructor(public dialog: MatDialog) { }

    ngOnInit() {
    }

    openDialog(modal:string): void {
        const dialogRef = this.dialog.open(RegisterDialog, {
            width: '480px',
            data: {name: modal}
        });
    }

    testEvent(value){
        console.log(value,"OOOOOOOOOOOOOOOOOOOO");
    }
}

@Component({
    selector: 'register-dialog',
    templateUrl: 'register-dialog.html',
    styleUrls: ['./new-time-register.component.scss']
})
export class RegisterDialog{

    constructor(
        public dialogRef: MatDialogRef<RegisterDialog>,
        @Inject(MAT_DIALOG_DATA) public data: DialogData) {}
    showAllPersons: Boolean = false;
    onNoClick(): void {
        this.dialogRef.close();
    }

    @Output() testEmit = new EventEmitter<string>();

    testEventEmitter(){
        console.log('TTTTTTTTTTTTTTTTTT');
        this.testEmit.emit("Test EventEmitter");
    }
}

this is register-dialog.html file

<span class="panel-title" (click)='testEventEmitter()'>Computicate Trial Account Manager</span>

here is my child app-new-time-register html file

<register-dialog (testEmit)='testEvent($event)'></register-dialog>

here is a child component

testEvent(value){
        console.log(value,"OOOOOOOOOOOOOOOOOOOO");
    }

Solution

  • Refering to your stackblitz, everything works with a little changes.

    You have to add the RegisterDialog in the app.module.ts.

     declarations: [AppComponent, HelloComponent, RegisterDialog]
    

    Also in the app.component.html you have to add the $event variable to the emitter:

    <register-dialog (testEmit)='checkEvent($event)'></register-dialog>
    

    Live example:

    https://stackblitz.com/edit/angular-stack-55945887?file=src%2Fapp%2Fapp.component.html