Home > Net >  Want to call function in child component from parent component
Want to call function in child component from parent component

Time:02-05

I have one component with name Company and from that component I am opening one popup modal, below is code for that.

Now in that popup modal user is uploading file and submit it, and then I am calling API.

Once API return success response then I want to call one function from Company component in that popup modal component.

html code

<div >
   <button color="primary" (click)="openUploadDocumentDialog()">
      Add Other Documents
   </button>
</div>

ts file code

public openUploadDocumentDialog() : void {
   const dialogRef = this.dialog.open(UploadDocumentDialogComponent, {
     width: '50vw',
     panelClass: ['documentsUploadDialog', 'ceqUserDialog'],
     data: {
        companyid: this.route.snapshot.params['company_guid']
      }
    });
  }

Now in this upload document dialog component user is uploading file, so once user upload file then click on Save then I am calling API.

It is successfully calling it. What I want is once this API get called successfully and returned response then I want to call method from Company component.

Upload-document-dialog.ts file

public uploadFileHandler(): void {
     this.apiService.uploadDocumentFile(this.uploadedFile)
       .subscribe({
         next: (event) => {
           if (event.data) {
           **// here I want to call function from Parent company dialog.**
             this.dialogRef.close(event.data);
           }
         },
         error: (err) => {
           this.snackBar.open('Connect error! Please try again!', 'Ok', {
             duration: 2000,
           });
         },
       });
  }

CodePudding user response:

This is the way I would go about solving the problem. I think in general it is 'bad practice' to call a function from the parent from the dialog box. So to get around this we would do the following.

Subscribe to dialogRef.afterClosed() call.

For example you could do something like this on the Company component

.html

<div >
   <button color="primary" (click)="openUploadDocumentDialog()">
      Add Other Documents
   </button>
</div>

.ts

public openUploadDocumentDialog() : void {
   const dialogRef = this.dialog.open(UploadDocumentDialogComponent, {
     width: '50vw',
     panelClass: ['documentsUploadDialog', 'ceqUserDialog'],
     data: {
        companyid: this.route.snapshot.params['company_guid']
      }
    });

    dialogRef.afterClosed().subscribe(response=> {
       // 'response' will be 'event.data' from this.dialogRef.close(event.data)
     })
  }
  • Related