В родительском компоненте
Сначала вам нужно импортировать ViewContainerRef из @angular/core.
create_dialog_component.ts
import { ViewContainerRef } from '@angular/core';Затем вам нужно внедрить ViewContainerRef в ваш компонент.
inject_viewcontainer.ts
constructor(private viewContainer: ViewContainerRef) {
}Теперь вы можете добавить этот метод для создания и отображения компонента диалога:
show_dialog_method.ts
showMyDialog(): void {
const component = this.viewContainer.createComponent(MyDialogComponent);
// You can access ANY public class method from MyDialogComponent
component.instance.setVisible(true);
}Компонент диалога
Этот компонент действительно ничем не примечателен. Это просто диалог с некоторыми методами, такими как setVisible(), доступными извне.
my_dialog_component.ts
export class MyDialogComponent {
visible = false;
constructor() {
}
public setVisible(visible: boolean = true) {
this.visible = visible;
}
submit() {
// TODO: What to do when the dialog is submitted
}
}my_dialog.component.html
<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>Вы также можете реализовать @Output() для генерации события, когда пользователь нажимает кнопку Save.
my_dialog_output.ts
export class MyDialogComponent {
// Typically you would emit a more complex data type.
@Output() saved = new EventEmitter<string>();
submit() {
this.saved.emit("some data");
}
}
Check out similar posts by category:
Angular Typescript
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow