Wie man eine Dialog-Komponente in Angular dynamisch erstellt

In der Eltern-Komponente

Zuerst müssen Sie ViewContainerRef aus @angular/core importieren.

create_dialog_component.ts
import { ViewContainerRef } from '@angular/core';

Dann müssen Sie ViewContainerRef in Ihre Komponente injizieren.

inject_viewcontainer.ts
constructor(private viewContainer: ViewContainerRef) {
}

Nun können Sie diese Methode hinzufügen, um die Dialog-Komponente zu erstellen und anzuzeigen:

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);
  }

Die Dialog-Komponente

Diese Komponente ist wirklich nichts Besonderes. Sie ist nur ein Dialog, mit einer Methode wie setVisible() verfügbar.

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>

Sie könnten auch ein @Output() implementieren, um ein Ereignis auszulösen, wenn der Benutzer auf die Save-Schaltfläche klickt.

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