简体   繁体   中英

Angular EventEmitter exposing value to parent component

In my Angular application I have a child grid component inside of my parent component, and I am trying to emit some data from my child grid to the parent container. I have used event emitter to try to "emit" that value to the parent, but when I try to access that variable that contains the data in the parent component it logs as undefined.

Here is what I have inside of my child component:

@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>

As you can see, I am trying to "emit" this.childRowData to my parent.

In my parent component I try to access it in a method like so:

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

This does not work because childRowData is undefined. Do I need to do something specific to have my parent component "listen" for the event? Also, do I really need an event emitter for this? Can't I just get childRowData as a global variable via a service? EventEmitter seems overkill in this case...

To get access to the outputted event, the template of the parent component should have a line like this somewhere:

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

and then in the parent component's ts file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM