How to return data from MatBottomSheet to its parent component?

Viewed 3543

I have an bottomsheet with an input field and two buttons submit and cancel.

Parent Component HTML

<div class="something" (click)="openBottomSheet()"></div>

Parent Component TS

import { MatBottomSheet } from "@angular/material";


constructor(private bottomsheet: MatBottomSheet) { }

openBottomSheet(): void {
   this.bottomsheet.open(BottomsheetComponent);
}

BottomSheet Component HTML

<mat-form-field>
  <input type="password" matInput placeholder="Password" [formControl]="password">
</mat-form-field>
<button mat-button  (click)="closeBottomSheet()">Cancel</button>
<button mat-button  (click)="checkPassword()">Confirm Password</button>

BottomSheet Component TS

import { MatBottomSheetRef } from "@angular/material";

constructor(private bottomsheet: MatBottomSheetRef<BottomsheetComponent>){}

closeBottomSheet(){
  this.bottomsheet.dismiss();
}

checkPassword(){
  //Here I need to pass data to parent component
}

In the input field user will enter data, on clicking submit a network call will be done, if it returns response 200 then I need to return a boolean from bottomsheet to its parent component.\

How can I achieve the above?

Will I use @Output() to do that like we do with components, if yes, how to use it here in bottomsheet?

1 Answers

You can use the bottom sheet reference and the observable provided by it. I have used inline comment for more details.

You can find more details about bottom sheet here- https://material.angular.io/components/bottom-sheet/overview

// Parent component
import { MatBottomSheet } from "@angular/material";


constructor(private bottomsheet: MatBottomSheet) { }

openBottomSheet(): void {
// Take refernce of bottom sheet
   const bottomSheetRef = this.bottomsheet.open(BottomsheetComponent);
   
   // subscribe to observable that emit event when bottom sheet closes
   bottomSheetRef.afterDismissed().subscribe((dataFromChild) => {
  console.log(dataFromChild);
});
}

// Child component
import { MatBottomSheetRef } from "@angular/material";

constructor(private bottomsheet: MatBottomSheetRef<BottomsheetComponent>){}

closeBottomSheet(){
  //  pass the data to parent when bottom sheet closes.
  this.bottomsheet.dismiss(data);
}

checkPassword(){
  //Here I need to pass data to parent component
}

Related