Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open ng-bootstrap modal programmatically

I've got an angular 4 page including a ng-bootstrap modal. My code looks like this.

foo.html

[...]
<button class="btn btn-sm btn-secondary material-icons"
(click)="open(content)">search</button>

<ng-template #content let-c="close" let-d="dismiss">
    content in here
</ng-template>
[...]

foo.ts

[...]
constructor(private modalService: NgbModal) { }
[...]
open(content) {
   let options: NgbModalOptions = {
     size: 'lg'
   };

   this.modalService.open(content, options);
}
[...]

Now when I click the button the modal opens. What I want to do now is open the model on ngChanges.

ngOnChanges(changes: any) {
   open(content)
}

My problem is: How do I get the "content" here? Is there any way to get the ng-template programmatically? Thanks in advance!

like image 664
Christian Riese Avatar asked Jul 16 '17 20:07

Christian Riese


2 Answers

To access the content element inside the class, declare:

@ViewChild('content', { static: false }) private content;
                         ^for Angular8+

and add the corresponding import at the top of the class:

import { ViewChild } from '@angular/core';

and finally call open method for that element on change detection:

ngOnChanges(changes: any) {
   this.open(this.content);
}
like image 161
Vega Avatar answered Sep 21 '22 03:09

Vega


from Angular 8 you should also pass static option: {static: false} in ViewChild

import { ViewChild } from '@angular/core';

@ViewChild('content', { static: false }) private content;

constructor(private modalService: NgbModal) { }

this.modalService.open(this.content);
like image 29
Ivan Bagaric Avatar answered Sep 20 '22 03:09

Ivan Bagaric