Another way to create Angular UI Component is using Dialog from Angular Material. It is not recommended to replace all components with it but it is rather useful for interactive elements like pop-ups, warnings, errors, etc.
There are 7 steps on how to start using dialogs in your Angular project.
Step 1: Adjust Angular Material for your project and create a basic Angular component (current name example: MyCreatedDialog) and add dialog reference.
Import MatDialogRef from @angular/material and add it to the constructor.
class MyCreatedDialog implements OnInit {
constructor (
public dialogRef: MatDialogRef<MyCreatedDialog>,
…
) {}
ngOnInit() {
…
}
…
}
Step 2: Set modules in app.module.ts.
Import MatDialogModule, MatButtonModule (and others if needed) from Angular Material to app.module.ts and imported your MyCreatedDialog.component.ts.
Add your imported component to declarations and entryComponents of NgModule.
Add needed dialog modules to import of NgModule.
Example:
@NgModule({
declarations: [...,
MyCreatedDialog
],
entryComponents: [...,
MyCreatedDialog
],
imports: [...,
MatDialogModule,
MatButtonModule
],
…
})
Step 3: Import MyCreatedDialog into its father component (current name: FatherComponent). Import MatDialog from Angular Material and add it to the constructor.
Example:
class FatherComponent {
constructor(
…,
private dialog: MatDialog
){}
...
}
Step 4: Control dialogs: open and get outputs.
Example:
openMyCreatedDialog() {
const myCreatedDialogRef = this.dialog.open(MyCreatedDialog);
myCreatedDialogRef.afterClosed().subscribe((res) => {
//do things according to the received response and the aim
})
}
Step 5: Add data input to MyCreatedDialog.
Add it to the function that opens the dialog:
openMyCreatedDialog() {
const myCreatedDialogRef = this.dialog.open(MyCreatedDialog, { data: { title: I am a dialog } }););
myCreatedDialogRef.afterClosed().subscribe((res) => {
//do things according to the received response and the aim
})
}
Step 6: Use passed data in MyCreatedDialog.
Import MAT_DIALOG_DATA from @angular/material and inject it in the constructor. Import Inject from @angular/core as well.
class MyCreatedDialog implements OnInit {
dialogTitle: string;
constructor (
public dialogRef: MatDialogRef<MyCreatedDialog>,
@Inject(MAT_DIALOG_DATA) public data: any,
…
){}
ngOnInit() {
this.dialogTitle = this.data.title;
}
…
}
Step 7: Add function to html file of MyCreatedDialog.
Example:
<button (click)=openMyCreatedDialog(“New meaningful title”)></button>
Step 8 - Extra: continue enjoying Angular :)
Top comments (0)