Search code examples
jsonangularangular-formsangular-formly

Open modal form containing form created from ngx-formly from another ngx-formly form


I'm currently using ngx-formly to dynamically create a bunch of Angular forms from JSON, which works really nicely. I have a peculiar use case where a custom button on a form, should open a modal dialog containing another form on click, which would also contain a form created using ngx-formly. The example I saw on the ngx-formly site use a custom button, and creates a custom component with .ts files, but I want to avoid that since I would have several forms doing this, and I don't want to create different components for this.

Is there a way to trigger a modal dialog from an ngx-formly form, to show the modal with ngx-formly form without having to create multiple components(.ts) files for them?


Solution

  • Common Bootstrap Model with dynamic data

    modal.service.ts

    import {Injectable} from '@angular/core';
    import {ModalModel} from './modal.model';
    import {Subject} from "rxjs/Subject";
    
    declare let $: any;
    
    @Injectable()
    export class ModalService {
    
      modalData = new Subject<ModalModel>();
    
      modalDataEvent = this.modalData.asObservable();
    
      open(modalData: ModalModel) {
    
        this.modalData.next(modalData);
    
        $('#myModal').modal('show');
      }
    
    }
    

    modal.component.ts

    import { Component } from '@angular/core';
    import { ModalService } from './modal.service';
    import {ModalModel} from './modal.model';
    
    declare let $: any;
    
    @Component({
      selector: 'app-modal',
      templateUrl: './modal.component.html',
      styleUrls: [ './modal.component.css' ]
    })
    export class ModalComponent  {
    
      modalData: ModalModel;
    
      constructor(private modalService: ModalService) {
        this.modalService.modalDataEvent.subscribe((data) => {
          this.modalData = data;
        })
      }
    
    }
    

    calling this service from any component

    import { Component } from '@angular/core';
    import { ModalService } from '../modal/modal.service';
    import { ModalModel } from '../modal/modal.model';
    
    
    declare let $: any;
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: [ './home.component.css' ]
    })
    export class HomeComponent  {
    
      modelData = new ModalModel();
    
      constructor(private modalService: ModalService) {
    
      }
    
      open() {
        this.modelData.header = 'This is my dynamic HEADER from Home component';
        this.modelData.body = 'This is my dynamic BODY from Home component';
        this.modelData.footer = 'This is my dynamic footer from Home component';
        this.modalService.open(this.modelData);
      }
    }