如何在angular7中使用EventEmitter

how to use EventEmitter in angular7

我在一个文件中定义了我的组件,我想将数据形式 parent 发送到 child 组件 parent 功能正常但 eventEmitter 不发出

这是我的组件文件有两个组件

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

这是 register-dialog.html 文件

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

这是我的childapp-new-time-registerhtml文件

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

这里有一个child组件

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

参考你的 stackblitz,稍作改动后一切正常。

您必须在 app.module.ts 中添加 RegisterDialog

 declarations: [AppComponent, HelloComponent, RegisterDialog]

同样在 app.component.html 中,您必须将 $event 变量添加到发射器:

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

实例:

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