1

I want to close only currently opened modal in angular using NgbModal. but 'dismissAll()' method of NgbModal closes all the currently opened modals.

I Created Two Entry Components in the Projects

  • ConsumerList //Main Component

    -AddConsumer //Entry Component //ChildModal

    -ShowAllConsumers //Entry Component //ParentModal

My Code :

    **//ShowAllConsumers.html  (Parent Modal)**

    <div class="modal-header">
      <div class="col-md-6">
        <h4>Consumers</h4>
      </div>
      <div class="col-md-6">
        <button style="float: right" type="submit" mat-raised-button color="primary" (click)="CloseModal()">
          Back
        </button>
      </div>

    </div>
    <div class="modal-body">
      <div class="row">
        <div class="col-md-12" id="gMap" style="min-height: 550px;width: 100%;height:100%">
        </div>
      </div>
    </div>

    <ng-template id='CLocation' #Consumer let-c="close" let-d="dismiss">
      <kt-AddConsumer [InputModel]="this.SelectedConsumer"></kt-AddConsumer>
    </ng-template>

    **//AddConsumer.html (Child Modal)**

    <div class="modal-header">
        <h4>Edit Consumer </h4>
    </div>
    <div class="col-md-6">
        <button style="float: right" id = "btnBack" mat-raised-button color="primary" (click)="CloseModal()">
            Back
        </button>
        <button style="float: right;margin-right: 10px;"
            *ngIf="this.Operation === 'ADD'" type="submit"
            mat-raised-button color="primary" (click)="SaveConsumer()">
            Save
        </button>
        <button style="float: right;margin-right: 10px;"
            *ngIf="this.Operation === 'EDIT'" type="submit"
            mat-raised-button color="primary" (click)="SaveConsumer()">
            Edit
        </button>

    </div>
    <div class="modal-body">
        <div class="row">
            <div class="col-md-12" id="map" style="min-height: 550px;width: 100%;height:100%">
            </div>
         </div>
     </div>

output of above code is :

output

**//ShowAllConsumers.ts**


import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
declare const google: any;

@Component({
  selector: 'kt-ShowAllConsumers',
  templateUrl: './ShowAllConsumers.component.html',
  styleUrls: ['./ShowAllConsumers.component.scss']
})
export class ShowAllConsumersComponent implements OnInit {
  @Input() InputModel: ConsumerModel[];
  AreaCoordinates: AreaGeoCoordinates[];
  @ViewChild('Consumer') ConsumerRef: ElementRef;
  gMap: any;
  marker: any;
  Operation: string;
  SelectedConsumer: ConsumerModel;

  constructor(
    public _ngZone: NgZone,
    public chRef: ChangeDetectorRef,
    private ngbModalService: NgbModal) { }

  ngOnInit() {
    window["angularComponentRef"] = { component: this, zone: this._ngZone };
    google.maps.event.addDomListener(window, "load", this.InitializeMap());
  }

  InitializeMap() {
    this.gMap = new google.maps.Map(document.getElementById('gMap'), {
      zoom: 10,
      center: { lat: 18.519834, lng: 73.857944 },
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    this.ShowCoordinates();
  }

  OpenLocationModal(AreaName, AreaRefNo, ConsumerAddress, ConsumerName, ConsumerNo, DistributorID, Latitude, Longitude, MobileNo, Pin, Source, UniqueConsumerId) {
    var m = new ConsumerModel();
    m.AreaName = AreaName;
    m.AreaRefNo = AreaRefNo;
    m.ConsumerAddress = ConsumerAddress;
    m.ConsumerName = ConsumerName;
    m.ConsumerNo = ConsumerNo;
    m.DistributorID = DistributorID;
    m.Latitude = Latitude;
    m.Longitude = Longitude;
    m.MobileNo = MobileNo;
    m.Pin = Pin;
    m.Source = Source;
    m.UniqueConsumerId = UniqueConsumerId;
    debugger;
    this.SelectedConsumer = m;
    //Opening the child modal
    var modalRef1 = this.ngbModalService.open(this.ConsumerRef, {
      windowClass: 'modalclass2',
      centered: true,
      size: "lg",
      backdrop: "static"
    });
    modalRef1.result.then(
      () => {
        alert("Close button clicked")
      }
      });
  }



  CloseModal() {
    this.ngbModalService.dismissAll();
  }

}

**//AddConsumer.ts**

import { Component, OnInit, Input, ChangeDetectorRef, Output, EventEmitter, ViewChild } from '@angular/core';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalDirective } from 'ngx-bootstrap/modal';

@Component({
  selector: 'kt-AddConsumer',
  templateUrl: './AddConsumer.component.html',
  styleUrls: ['./AddConsumer.component.scss'],
  providers: [AreawiseConsumerListComponent,NgbActiveModal]
})
export class AddConsumerComponent implements OnInit {
  @Input() InputModel: ConsumerModel;
  constructor(
    private activeModal: NgbActiveModal) { }

  ngOnInit() {

  }

  CloseModal() {
    this.activeModal.dismiss();
  }

}

When I click on Back button of child Modal, All two modal getting closed but I want to close only child modal.

Is there any way to achieve the same ?

Tejas
  • 381
  • 1
  • 7
  • 25
  • https://ng-bootstrap.github.io/#/components/modal/api – msmani Jul 24 '19 at 12:26
  • I tried for the NgbActiveModal but it is not working – Tejas Jul 24 '19 at 12:29
  • @Tejas i will recommend you to create a reusable modal component , check this thread : https://stackoverflow.com/questions/44360691/how-to-make-a-modal-reusable-in-angular-2/56559002#56559002 – Joel Joseph Jul 24 '19 at 13:08

1 Answers1

0

In your AddConsumer.ts you need to inject a reference to NgbActiveModal and the selected consumer in the constructor.

You can also remove the hack code with the template and properties/input/binding for SelectedConsumer.

...
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

export class AddConsumer {
  constructor(
    @Inject('selectedConsumer') private selectedConsumer: ConsumerModel,
    private activeModal: NgbActiveModal,
    ...
  ) {
  }

  CloseModal() {
    this.activeModal.dismiss();
  }

}

Here is where you open the dialog, injecting the selectedConsumer:

OpenLocationModal(AreaName, AreaRefNo, ConsumerAddress, ConsumerName, ConsumerNo, DistributorID, Latitude, Longitude, MobileNo, Pin, Source, UniqueConsumerId) {
    var m = new ConsumerModel();
    m.AreaName = AreaName;
    m.AreaRefNo = AreaRefNo;
    m.ConsumerAddress = ConsumerAddress;
    m.ConsumerName = ConsumerName;
    m.ConsumerNo = ConsumerNo;
    m.DistributorID = DistributorID;
    m.Latitude = Latitude;
    m.Longitude = Longitude;
    m.MobileNo = MobileNo;
    m.Pin = Pin;
    m.Source = Source;
    m.UniqueConsumerId = UniqueConsumerId;
    //Opening the child modal
    var modalRef1 = this.ngbModalService.open(AddConsumerComponent, {
        windowClass: 'modalclass2',
        centered: true,
        size: "lg",
        backdrop: "static",
        injector: Injector.create({
            providers: [{
                provide: 'selectedConsumer', //maybe use an InjectionToken instead of a string
                useValue: m,
            }],
            parent: this.injector,
        }),
    });
    modalRef1.result.then(
        () => {
            alert("Close button clicked")
        }
    });
Andrei Tătar
  • 7,872
  • 19
  • 37
  • I did the same code and got the error : NullInjectorError: No provider for NgbActiveModal! ....... then I also provide NgbActiveModal in component providers but still it is not working – Tejas Jul 24 '19 at 12:33
  • See if this helps. https://stackoverflow.com/questions/44211922/ng-bootstrap-modal-component-no-provider-error – Immanuel Jul 24 '19 at 12:37
  • 1
    @Tejas you don't need to add NgbActiveModal in the providers list. Also post the code where you open this modal. If you use the NgbModal service to show it, it provides the active modal ref. – Andrei Tătar Jul 24 '19 at 12:45
  • I have updated the code ......Yes.. I used NgbModal Service for opening of modal but it not provides Active modal ref – Tejas Jul 24 '19 at 12:54
  • 1
    @Tejas the problem is in the way you open the modal... You should inject the `SelectedConsumer` in `AddConsumer`, don't do that hack. I'll update my answer shortly. – Andrei Tătar Jul 24 '19 at 12:58
  • Sorry Sir...I tried your code...but still getting error : NullInjectorError: No provider for NgbActiveModal.....actually I injected the selectedCosumer in following way : – Tejas Jul 24 '19 at 13:13
  • @Tejas are you sure you also updated `ShowAllConsumersComponent`? – Andrei Tătar Jul 24 '19 at 13:14
  • Yes Sir...I am sure ... I added the injector provided by you – Tejas Jul 24 '19 at 13:15
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196929/discussion-between-tejas-and-andrei-ttar). – Tejas Jul 24 '19 at 13:17