angularjsHow do I create a yes/no dialog box using Angular?
Creating a yes/no dialog box using Angular is a straightforward process. First, you need to import the MatDialogModule from the @angular/material package into your app.module.ts file.
import { MatDialogModule } from '@angular/material';
@NgModule({
imports: [
...
MatDialogModule,
],
...
})
export class AppModule { }
Then, you need to create a component for the dialog box. The component should include an HTML template for the dialog box and the TS file should include the code for the dialog box.
@Component({
selector: 'dialog-box',
templateUrl: 'dialog-box.html',
})
export class DialogBoxComponent {
constructor(
public dialogRef: MatDialogRef<DialogBoxComponent>,
@Inject(MAT_DIALOG_DATA) public data: DialogData
) {}
onNoClick(): void {
this.dialogRef.close();
}
}
The HTML template for the dialog box should include the two buttons for the yes/no selection.
<h1 mat-dialog-title>Dialog Box</h1>
<div mat-dialog-content>
<p>Do you want to continue?</p>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">No</button>
<button mat-button [mat-dialog-close]="true">Yes</button>
</div>
Finally, you need to open the dialog box from the component where you want to use it.
openDialog(): void {
const dialogRef = this.dialog.open(DialogBoxComponent, {
width: '250px',
data: {name: this.name, animal: this.animal}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
The code above will create a yes/no dialog box using Angular.
Code explanation
**
- Importing MatDialogModule:
import { MatDialogModule } from '@angular/material';
- Creating DialogBoxComponent:
@Component({selector: 'dialog-box', templateUrl: 'dialog-box.html'})
- HTML template for the dialog box:
<h1 mat-dialog-title>Dialog Box</h1> <div mat-dialog-content> <p>Do you want to continue?</p> </div> <div mat-dialog-actions> <button mat-button (click)="onNoClick()">No</button> <button mat-button [mat-dialog-close]="true">Yes</button> </div>
- Opening the dialog box:
openDialog(): void { const dialogRef = this.dialog.open(DialogBoxComponent, { width: '250px', data: {name: this.name, animal: this.animal} }); dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); }); }
## Helpful links
More of Angularjs
- How can I become an Angular expert from a beginner level?
- How can I create an editable AngularJS application?
- How can I use the Yandex Map API with AngularJS?
- How can I use Angular to zoom in and out of a div?
- How do I install Yarn using Angular?
- How do I use AngularJS to zoom in on an image?
- How do I use Angular Zone to run my code?
- How do I use Angular to zip files?
- How do I use Angular Zone to detect and run Angular change detection?
- How do I copy an element in AngularJS?
See more codes...