Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use parent component's variable, in its method that is invoked by a child component

I’m using a child component:

<app-photo-editor [addPhotoUrlExtension]="'users/add-photo'" [onUploadSuccess]="onUploadPhotoSuccess"
                [deletePhoto]="onDeletePhoto"></app-photo-editor>  

and passing it the onUploadPhotoSuccess function:

 onUploadPhotoSuccess(response: any) {
    if (response) {
      const photo = JSON.parse(response);
      this.member.photoUrl = photo.url;  // offending line
      ...

On the child component, I accept the function, and invoke the parent’s function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export class PhotoEditorComponent implements OnInit {
  @Input() onUploadSuccess: (response: any) => void;

this.uploader.onSuccessItem = (item, response, status, headers) => {
      if (response) {
        this.onUploadSuccess(response);
      }
    }  

This gives an error on the offending line (marked above), saying:

core.js:6498 ERROR TypeError: Cannot set properties of undefined (setting 'photoUrl')
    at PhotoEditorComponent.onUploadPhotoSuccess [as onUploadSuccess] (member-edit.component.ts:67:27)
    at FileUploader.uploader.onSuccessItem (photo-editor.component.ts:60:14)
    at FileUploader._onSuccessItem (ng2-file-upload.js:1326:1)
    at XMLHttpRequest.xhr.onload [as __zone_symbol__ON_PROPERTYload] (ng2-file-upload.js:1073:29)
    at XMLHttpRequest.wrapFn (zone.js:763:1)
    at ZoneDelegate.invokeTask (zone.js:406:1)
    at Object.onInvokeTask (core.js:28679:1)
    at ZoneDelegate.invokeTask (zone.js:405:1)
    at Zone.runTask (zone.js:178:1)
    at ZoneTask.invokeTask [as invoke] (zone.js:487:1)  

Which means this.member is undefined, now on one hand it does makes sense I would have needed to pass it to the child component, but on the other, I THINK this worked as is.. So I’m not sure what’s the right solution..

>Solution :

This is because you’re passing a regular function to another component and therefore the this keyword is not referring to the original component.

You should either use arrow functions for onUploadPhotoSuccess or bind this to it.

onUploadPhotoSuccess = (response: any) => {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading