首页 文章

Angular EventEmitter向父组件公开值

提问于
浏览
0

在我的Angular应用程序中,我的父组件中有一个子网格组件,我试图从子网格中向父容器发出一些数据 . 我已经使用事件 Launcher 尝试将该值“发送”到父级,但是当我尝试访问包含父组件中的数据的变量时,它会记录为未定义 .

这是我的子组件中的内容:

@Component({
    selector: 'row-details',
    templateUrl: './row-details.component.html'
})

export class ChildRowDetailsComponent {

childRowData: any[];

@Output() emitRowData = new EventEmitter<any>();

constructor(...) {}

createRowData(gridValues) {
        let rowData: any[] = [];
        for (let i = 0; i < gridValues.length; i++) {
            let data = gridValues[i % gridValues.length];
            rowData.push({
               ...
            });
        }
        this.childRowData = rowData;

        this.emitRowData.emit(this.childRowData);
    }

...}

child.component.html:

<ag-grid-angular #agGrid style="width: 100%; height:100%" class="ag-material grid-Holdings"
                 [rowData]="rowData"
                 [getRowHeight]="getRowHeight"
                 headerHeight="35"
                 [columnDefs]="columnDefs"
                 [gridOptions]="gridOptions"
                  (gridReady)="onGridReady($event)">

</ag-grid-angular>

如您所见,我正在尝试将this.childRowData“发出”给我的父母 .

在我的父组件中,我尝试使用如下方法访问它:

...
getChildRowData(params, childRowData) {
    // I would like to do something with childRowData
}
...

这不起作用,因为未定义childRowData . 我是否需要做一些特定的事情让我的父组件“听”这个事件?另外,我真的需要一个事件 Launcher 吗?我不能通过服务将childRowData作为全局变量吗?在这种情况下,EventEmitter看起来有点过头了......

1 回答

  • 0

    要访问输出的事件,父组件的 template 应该有一个这样的行:

    <row-details (emitRowData)="getChildRowData($event)"></row-details>
    

    然后在父组件的ts文件中

    getChildRowData(childRowData) {
        /* do stuff with the data here */
    }
    

相关问题