如何在 Angular 中动态创建对话框组件
在父组件中
首先,你需要从 @angular/core 导入 ViewContainerRef。
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