简体   繁体   中英

Angular4 Passing data from parent to child, emit not working

I'm trying to emit data from the parent component to the child component, however I'm facing a problem with my ng2-smart-table that is in the way of emitting. In my parent component I make use of the ng2-smart-table, which uses userRowSelect (a standard function), when I select a row in the table, I get all the data from that row. The data from that row I want to pass to my child component. I tried using a shared service, input and emitting, none of them have worked so far. Below are code snippets of the two components. Any suggestions on what to do?

Parent html:

<ng2-smart-table [settings]="settings" [source]="data" (userRowSelect)="onRowSelect($event)"></ng2-smart-table>

Parent component:

@Output() passDataToViewPdf: EventEmitter<any> = new EventEmitter();

  ngOnInit() {
      this.reportService.getReportsTemplates().subscribe(response => this.data = response);
  }

  onRowSelect(event): void {
      this.passDataToViewPdf.next(event);
      this.router.navigate(['/report-view-pdf', localStorage.getItem('siteId')]);
  }

Child component:

    @Input() template;

    public handleEvent(event) {
            // get data from passDataToViewPdf emitter
        }
    ngOnInit() { this.template = // get data from handleEvent}

That's because Angulars EventEmitter has emit method to emit value. Look at docs

It should be

this.passDataToViewPdf.emit(event);

However looking at your code EventEmitter is defined in parent component, so your parent component is emitting value to it's parent not to child.

It should look like this.

Child component

@Input() template;
@Input() set pdf(newPdf) {
   this._pdf = newPdf;
   this.handleEvent(newPdf);
};
private _pdf;



public handleEvent(event) {
    // process your data
}
ngOnInit() { this.template = // get data from handleEvent}

Parent html template

<child-component [pdf]="pdfValueInParent"></child-component>

Parent component ts

onRowSelect(event): void {
      this.pdfValueInParent = event;
      this.router.navigate(['/report-view-pdf', localStorage.getItem('siteId')]);
  }

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