Search code examples
angularngx-bootstrap

How to get Input values from nested component modal ngx-bootstrap using angular


I am using ngx-bootstrp Modals. I have to use nested service-component modal for specific requirement.I have made live demo to show problem.

Demo

I want (for example) full name to appear in modal, first name from first modal and last name from second modal and be updated as user inputs.

import { Component, TemplateRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';


@Component({
    selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent{
  modalRef: BsModalRef;
  constructor(private modalService: BsModalService) {}
  person:any={}
  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }

  openModalWithComponent() {

    this.modalRef = this.modalService.show(ModalContentComponent);
    this.modalRef.content.title = 'Modal with component';

  }
}

/* This is a component which we pass in modal*/

@Component({
  selector: 'modal-content',
  template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">{{title}}</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
    <input type="text" placeholder="Last Name">

    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="modalRef.hide()">Close</button>
    </div>
  `
})
export class ModalContentComponent {
  title: string;
  constructor(private modalService: BsModalService) {}
}

I found this SO post found to be similar, it is not use full for my requirement.

How to achieve above requirement?

Thanks for your time..


Solution

  • You can use a shared object for both modal. Not a perfect solution but it should help.

    First modal

    person = {fname: '', lname: ''};
    
    openModal() {
       this.modalRef = this.modalService.show(ModalContentComponent);
       this.modalRef.content.person = this.person;
    }
    

    Second modal template

    <input type="text" *ngIf="person" placeholder="Last Name" [(ngModel)]="person.lname">
    

    Example: https://stackblitz.com/edit/angular-nested-component-modal-ngx-bootstrap-not-working-k4pglr?file=app/app.component.ts