Reputation: 28
I'm bulding an app in Angular2 with visual studio 2015: There are two buttons in the main page that both give a same popup window. Everything worked good until I decided to make a separate component for this modal. So buttons stay still in main page and modal is now in another component. But now I got the error :Cannot read property 'show' of undefined! on my show function. Here is modal.component.ts:
import { Component, OnInit, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
@Component({
selector: 'app-info-modal',
templateUrl: './info-modal.component.html',
styleUrls: ['./info-modal.component.scss']
})
export class InfoModalComponent implements OnInit {
@ViewChild('lgModal') public lgModal:ModalDirective;
constructor() { }
ngOnInit() {
}
showInfoModal = () => {
this.lgModal.show();
};
}
Here is modal.component.html:
<div bsModal #lgModal="bs-modal" [config]="{backdrop: 'static'}" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title pull-left">what is it about?</h2>
<button type="button" class="close pull-right" (click)="lgModal.hide()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>content of the window.....</p>
</div>
</div>
</div>
</div>
The button in main page component html:
<button class="btn-default btn pull-right next" (click)="showModal()"> privacy <i class="fa fa-fw fa-chevron-right"></i></button>
Homepage component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor(){
}
ngOnInit() {
}
showModal() {
this.infoModal.showInfoModal();
}
Do anyone has any idea? I don't know where I made mistake!
Upvotes: 1
Views: 6943
Reputation: 41533
You should be using the below for your ViewChild
reference
@ViewChild(ModalDirective) public lgModal:ModalDirective;
Update 1 : Based on revised question
You are missing the infoModal
refernce as below,
export class HomeComponent implements OnInit {
@ViewChild(InfoModalComponent) infoModal : InfoModalComponent; ////// missing declaration
ngOnInit() {
}
showModal() {
this.infoModal.showInfoModal();
}
Note : As you are using this.infoModal
you need to declare it as above, else you can use them in the HTML itself as
<button class="btn-default btn pull-right next" (click)="infoModal.showInfoModal()">
Show Information
</button>
<app-info-modal #infoModal> </app-info-modal>
Upvotes: 2