Ngx-bootstrap: Auto open modal from components

Created on 3 Aug 2016  路  12Comments  路  Source: valor-software/ngx-bootstrap

We want to open modal on page load/autoshow, I'm calling show modal function in ngOnInit function.code of same is as follows

componet.ts file

import { Component, OnInit, ViewChild } from '@angular/core';

import { MODAL_DIRECTIVES, BS_VIEW_PROVIDERS } from 'ng2-bootstrap/ng2-bootstrap';
import { ModalDirective } from 'ng2-bootstrap/components/modal/modal.component';
import { Router } from '@angular/router';

import { UserService } from '../user.service';
import { UserFBService } from '../user-facebook.service';
import { UserModel } from '../user.model';

@Component({
moduleId: module.id,
selector: 'app-user-type',
templateUrl: 'usertype.component.html',
directives: [MODAL_DIRECTIVES],
viewProviders: [BS_VIEW_PROVIDERS],
exportAs: 'usertype'
})
export class UsertypeComponent implements OnInit {
@ViewChild('UsertypeModal') UsertypeModal: ModalDirective;
constructor(private userService: UserService, private router: Router,
private userModel: UserModel) {
console.log('In UsertypeComponent');

}
ngOnInit() {
this.showModal();
}
showModal() {
console.log('Clicked on showModal');
this.UsertypeModal.show();
}

hideModal() {
console.log('Clicked on hideModal');
this.UsertypeModal.hide();
}
}

componet.html file

Most helpful comment

Use ngAfterViewInit instead of ngOnInit. The ViewChildis still undefined when the component is initialized and the showModal() function is run.

All 12 comments

I'm getting this same error.

@kharatps02
I believe, since you are accessing the ViewChild with UsertypeModal, you need to define a local template variable with that name. On your div.modal-body.custom-pop-modal element, you need to add #UsertypeModal="bs-modal", like so:
<div #UsertypeModal="bs-modal" class="modal-body custom-pop-modal">

Use ngAfterViewInit instead of ngOnInit. The ViewChildis still undefined when the component is initialized and the showModal() function is run.

Got same error too sometimes

@djsiroky thanks for help!

@djsiroky Saved my day.

I too stumbled upon this. Thinking about it, then it makes sense however put it in a ngOnInit out of habit.
Cheers!

@djsiroky Thank you so much for your help. I had been trying to solve the bug the whole working day.

Big thanks to @djsiroky

Thanks @djsiroky!
For those that had my problem:
If you are getting this during a test for example in jasmine. Make sure you do

fixture.detectChanges();
BEFORE:
ModalDirective.show() is called.

Regards!

Thanks @josead, that's been the exact reason of my problem during jasmine tests.

If you want to show modal on load of component, you can use 'show' attribute of config applied to modal.
ex. [config]='{show: true, ....}'
Reference:
https://valor-software.com/ngx-bootstrap/#/modals#directive-auto-shown

Was this page helpful?
0 / 5 - 0 ratings