How to dynamically create dialog component in Angular
In the parent component
First, you need to import the ViewContainerRef
from @angular/core
.
import { ViewContainerRef } from '@angular/core';
Then, you need to inject the ViewContainerRef
into your component.
constructor(private viewContainer: ViewContainerRef) {
}
Now you can add this method to create and show the dialog component:
showMyDialog(): void {
const component = this.viewContainer.createComponent(MyDialogComponent);
// You can access ANY public class method from MyDialogComponent
component.instance.setVisible(true);
}
The dialog component
This component is really nothing special. It just a dialog, with some method such as setVisible()
exposed.
export class MyDialogComponent {
visible = false;
constructor() {
}
public setVisible(visible: boolean = true) {
this.visible = visible;
}
submit() {
// TODO: What to do when the dialog is submitted
}
}
<p-dialog header="My dialog" [(visible)]="visible" [modal]="true">
<div class="input-container">
<!-- TODO add your dialog content here -->
</div>
<!-- NOTE: Just as an example, "Save" and "Abort" buttons -->
<div class="row button-row mt-3">
<span class="p-buttonset">
<p-button pRipple icon="pi pi-check" (click)="submit()" label="Save"></p-button>
<p-button pRipple severity="danger" icon="pi pi-times" (click)="visible=false" label="Abort"></p-button>
</span>
</div>
</p-dialog>
You could also implement a @Output()
to emit an event when the user clicks the Save
button.
export class MyDialogComponent {
// Typically you would emit a more complex data type.
@Output() saved = new EventEmitter<string>();
submit() {
this.saved.emit("some data");
}
}