1

我有一个 CustomDialog,我将它用作确认对话框,并在其中将我的外部组件显示为模式对话框。我想在其中注入一个在 TS 文件中创建的动态 formGroup。在我使用 Metro4 组件之前,该组件在对话服务中具有如下方法:

<mat-dialog-content>
            <ng-template #renderComponent>'I used this section to show component'</ng-template>

            <div *ngIf="data.form" [formGroup]="form">
            'I want to inject formgroup hier'
            'like injecting as an formGroup in data.form parameter'
            </div>
</mat-dialog-content>

那是TS代码:

import { FormGroup } from '@angular/forms';
import { AfterViewInit, Component, Inject } from "@angular/core";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog";
import { ViewChild, ComponentFactoryResolver, ViewContainerRef, ComponentRef } from "@angular/core";

@Component({
  selector: 'custom-dialog',
  templateUrl: './custom-dialog.component.html',
  styleUrls: ['./custom-dialog.component.scss']
})
export class CustomDialogComponent implements AfterViewInit {
  @ViewChild("renderComponent", { read: ViewContainerRef })
  vcRef: ViewContainerRef;
  componentRef: ComponentRef<any>;

  form: FormGroup;

  constructor(public dialogRef: MatDialogRef<CustomDialogComponent>,
    private resolver: ComponentFactoryResolver,
    @Inject(MAT_DIALOG_DATA) public data: any) {
  }

  ngAfterViewInit() {
    const comp = this.resolver.resolveComponentFactory(this.data.component);
    this.componentRef = this.vcRef.createComponent(comp);
  }

  ngOnDestroy() {
    if (this.componentRef) {
      this.componentRef.destroy();
    }
  }
}

但现在我想使用 Angular Material UI,我想创建上面提到的东西。我想知道我该怎么做。

例如,我这样称呼我的 CustomDialog:

const myForm = new FormGroup({
      email: new FormControl('', [Validators.required,
      Validators.email])});

const dialogRef = this.dialogService.open(CustomDialogComponent,
      {
        hasBackdrop: true,
        disableClose: true,
        panelClass: 'myapp-no-padding-dialog',
        data: {
          title: 'Title',
          *formGroup: myForm*
        }
      });
4

0 回答 0