I assume you have Material installed in your npm and you already know how to create a project in Angular. Here, I am using Visual Studio Code for the implementation purpose.
So, let's create one component with one button such that when we click the button, it will open a component in a Modal Popup.
Use the below command and create one component.
ng g c PopupComponent
Add Material dialog in constructor and import the same from angular/material
- import { Component, OnInit } from'@angular/core';
- import { MatDialog } from'@angular/material';
- @Component({
- selector:'app-popup-component',
- templateUrl:'./popup-component.component.html',
- styleUrls: ['./popup-component.component.css']
- })
- exportclassPopupComponentComponentimplementsOnInit {
- constructor(privatedialog:MatDialog) { }
- ngOnInit() {
- }
- }
Add the following code in the HTML file.
- <button(click)="openDialog()">Click me</button>
Add the following code for the openDialog method in .ts file.
- openDialog(): void {
- constdialogRef = this.dialog.open(ModalComponent, {
- panelClass: 'detailsZoom',
- data: {
- name: 'modal',
- type: 'score',
- }
- });
- }
this.dialog.open(ModalComponent)
Here, modalComponent is the name of the component which will get loaded in the modal dialog popup. Create this component using ng g c component name command.
"panelClass" is the CSS class which is applied to the modal popup. You can have your own CSS class as well in the modal popup. For that, you just need to replace the name of the CSS file of yours.
In the data field, pass whatever you want to pass to your modal popup. Here, we are passing the name and type for the modal.
Add the below code to its .ts file for the modal component class.
- import { Component, Inject } from'@angular/core';
- import { MatDialogRef, MAT_DIALOG_DATA } from'@angular/material';
- @Component({
- selector:'app-modal',
- templateUrl:'./modal.component.html',
- styleUrls: ['./modal.component.css']
- })
- exportclassModalComponent {
- constructor(
- publicdialogRef:MatDialogRef<ModalComponent>,
- @Inject(MAT_DIALOG_DATA) publicdata:any) {
- console.log(this.data);
- }
- onNoClick():void {
- this.dialogRef.close();
- }
- }
@Inject is used to hold the data which you have passed from the popup component. You can log the data and see if what you have passed is getting logged or not.
Add the below code in html file of modal component
- <p>Dialog popup works </p>
Add the below code to close the popup
- <button(click)="onNoClick()">Close</button>
Since you are loading component in modal popup at run time, you need to add that comonent in "entry".
app.module.ts
Add the below line in app.module.ts.
entryComponents: [ModalComponent]
Now, you can run your project using ng serve command and load popup component in the browser. Click on "Click me" which will invoke the openDialog method. This will load your modal component in modal dialog popup.
Hope this blog will give you some idea how to use Material Modal Popup in Angular.