Angular Material Bottom Sheet Pass Data

By Arvind Rai, October 19, 2022
On this page we will learn to pass data to Material bottom sheet in our Angular Material application.
1. We can pass data to bottom sheet from the opener component as well as from application module.
2. To send data from opener component, create an instance of MatBottomSheetConfig and pass it as argument to open() method of MatBottomSheet.
3. The data field of MatBottomSheetConfig carries the data to be sent to bottom sheet.
4. To send data from application module, use MAT_BOTTOM_SHEET_DEFAULT_OPTIONS property.
5. In bottom sheet component, use injector MAT_BOTTOM_SHEET_DATA to receive data.
6. To return data from bottom sheet to opener component, pass data to dismiss() method in bottom sheet component and receive data in opener component by subscribing Observable obtained from afterDismissed() method.

Technologies Used

Find the technologies being used in our example.
1. Angular 13.1.0
2. Angular Material 13.3.9
3. Node.js 12.20.0
4. NPM 8.2.0

Passing Data to Bottom Sheet Component

A. Sending data from parent component
1. Data is passed to bottom sheet component using data property of MatBottomSheetConfig class. The MatBottomSheetConfig is a configuration class used when opening a bottom sheet.
2. The MatBottomSheetConfig is passed to open() method of MatBottomSheet.
Find the open method Angular doc.
MatBottomSheet.open(component: ComponentType<T>,
 config?: MatBottomSheetConfig<any> | undefined): MatBottomSheetRef<T, R> 
Opens a bottom sheet containing the given component.
Parameters:
1. component : Type of the component to load into the bottom sheet.
2. config : Extra configuration options.
Returns:
Reference to the newly-opened bottom sheet.

Find the code snippet.
constructor(private bottomSheet: MatBottomSheet) { }
openBottomSheet() {
  const config: MatBottomSheetConfig = {data: dataToBottomSheet};
  this.bottomSheetRef = this.bottomSheet.open(BottomSheetComponent, config);
} 
B. Receiving data in bottom sheet component
Material bottom sheet provides injection token MAT_BOTTOM_SHEET_DATA that can be used to access the data passed to a bottom sheet component.
constructor(@Inject(MAT_BOTTOM_SHEET_DATA) public data: any) { } 
The constructor parameter data contains the data sent to bottom sheet component. We can use this data in our HTML template.
<div *ngFor= "let e of  data">
    {{e.name}} - {{e.city}}
</div> 

Passing Data using Global Configuration

Data can also be passed to bottom sheet using global configuration. Material bottom sheet provides MAT_BOTTOM_SHEET_DEFAULT_OPTIONS constant that can be used to specify default bottom sheet options.
The MAT_BOTTOM_SHEET_DEFAULT_OPTIONS is configured in application module as following.
providers: [
  {
      provide: MAT_BOTTOM_SHEET_DEFAULT_OPTIONS,
      useValue: { data : DATA_TO_BOTTOM_SHEET, panelClass: 'mybottomsheet' }
  }
] 
Here useValue is using MatBottomSheetConfig instance. The data property of MatBottomSheetConfig class is used to pass data to bottom sheet.
In bottom sheet component, we can fetch data using injection token MAT_BOTTOM_SHEET_DATA.
constructor(@Inject(MAT_BOTTOM_SHEET_DATA) public data: any) { } 

Returning Value from Bottom Sheet to Parent Component

We can return data from bottom sheet to parent component while dismissing bottom sheet.
A. Pass the data to dismiss() method that closes the bottom sheet. The Parameter of dismiss() is result?: R where result is the data to be passed back to the bottom sheet opener component.
Find the code snippet for dismiss() method.
constructor(private bottomSheetRef: MatBottomSheetRef<BottomSheetComponent>) { }
closeBottomSheet() {
    const dataToReturn = {result: 'Success'};
    this.bottomSheetRef.dismiss(dataToReturn);
} 
B. In parent component, we call afterDismissed() method of MatBottomSheetRef class. The afterDismissed() method returns an observable that is notified when the bottom sheet is finished closing.
this.bottomSheetRef.afterDismissed().subscribe(data => {
   console.log('Return value: ', data);
}); 

Complete Example

A. Parent component

example.component.ts
import { Component } from '@angular/core';
import { MatBottomSheet, MatBottomSheetConfig, MatBottomSheetRef } from '@angular/material/bottom-sheet';
import { BottomSheetComponent } from './bottom-sheet.component';

@Component({
  selector: 'app-bottom-sheet',
  templateUrl: './example.component.html'
})
export class ExampleComponent {
  bottomSheetRef = {} as MatBottomSheetRef<BottomSheetComponent>
  constructor(private bottomSheet: MatBottomSheet) { }
  openBottomSheet() {
    const dataToBottomSheet = [
      { name: 'Mohan', city: 'Mathura' },
      { name: 'Shiv', city: 'Varanasi' },
      { name: 'Ram', city: 'Ayodhya' },
    ];
    const config: MatBottomSheetConfig = { data: dataToBottomSheet };
    this.bottomSheetRef = this.bottomSheet.open(BottomSheetComponent, config);
    this.bottomSheetRef.afterOpened().subscribe(() => {
      console.log('Bottom sheet is open.');
    });
    this.bottomSheetRef.afterDismissed().subscribe(data => {
      console.log('Return value: ', data);
    });
  }
} 
example.component.html
<button mat-raised-button (click)="openBottomSheet()">Open Bottom Sheet</button> 

B. Bottom sheet component

bottom-sheet.component.ts
import { Component, Inject } from '@angular/core';
import { MatBottomSheetRef, MAT_BOTTOM_SHEET_DATA } from '@angular/material/bottom-sheet';

@Component({
	templateUrl: './bottom-sheet.component.html'
})
export class BottomSheetComponent {
	constructor(private bottomSheetRef: MatBottomSheetRef<BottomSheetComponent>,
		@Inject(MAT_BOTTOM_SHEET_DATA) public data: any) { }
	closeBottomSheet() {
		const dataToReturn = { result: 'Success' };
		this.bottomSheetRef.dismiss(dataToReturn);
	}
} 
bottom-sheet.component.html
<div *ngFor= "let e of  data">
    {{e.name}} - {{e.city}}
</div>
<button mat-raised (click)="closeBottomSheet()">Close</button> 

C. Other files

data-to-bottom-sheet.ts
export const DATA_TO_BOTTOM_SHEET = [
    {name: 'Mohan', city: 'Mathura'},
    {name: 'Shiv', city: 'Varanasi'},
    {name: 'Ram', city: 'Ayodhya'},
  ]; 
app.component.ts
import {Component} from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
     <app-bottom-sheet></app-bottom-sheet>
  `
})
export class AppComponent {
} 
styles.css
.mybottomsheet {
	background-color: burlywood;
	color: blue;
	font-size: large;
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatBottomSheetModule } from '@angular/material/bottom-sheet';
import { MatButtonModule } from '@angular/material/button';
import { MAT_BOTTOM_SHEET_DEFAULT_OPTIONS } from '@angular/material/bottom-sheet';

import { AppComponent } from './app.component';
import { BottomSheetComponent } from './bottom-sheet.component';
import { ExampleComponent } from './example.component';
import { DATA_TO_BOTTOM_SHEET } from './data-to-bottom-sheet';

@NgModule({
      imports: [
            BrowserModule,
            BrowserAnimationsModule,
            MatBottomSheetModule,
            MatButtonModule
      ],
      declarations: [
            AppComponent,
            ExampleComponent,
            BottomSheetComponent
      ],
      providers: [
            {
                  provide: MAT_BOTTOM_SHEET_DEFAULT_OPTIONS,
                  useValue: { data: DATA_TO_BOTTOM_SHEET, panelClass: 'mybottomsheet' }
            }
      ],
      bootstrap: [
            AppComponent
      ]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Install Angular CLI using link.
2. Install Angular Material using link.
3. Download source code using download link given below on this page.
4. Use downloaded src in your Angular CLI application.
5. Run ng serve using command prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Material Bottom Sheet Pass Data

Reference

Bottom Sheet

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us