3

I have a CustomDialog and I use it as a confirm dialog box and show my external component in it as a modal dialog. I wanted to inject a dynamic formGroup that created in TS file in it. Before I used Metro4 component that has a method in dialog service as below:

<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>

and that is TS code:

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

But now I wanted to use Angular Material UI and I want to create something like mentioned above. I wanted to know how can I do that.

for example, I call my CustomDialog like this:

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

0 Answers0