我正在使用visual studio 2015在Angular2中构建应用程序:主页面中有两个按钮,它们都提供相同的弹出窗口。一切顺利,直到我决定为这个模态制作一个单独的组件。因此按钮仍保留在主页面中,而模态现在位于另一个组件中。但现在我得到了错误:无法读取未定义的属性'show'!在我的节目功能。 这是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();
};
}
这是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>
主页面组件html中的按钮:
<button class="btn-default btn pull-right next" (click)="showModal()"> privacy <i class="fa fa-fw fa-chevron-right"></i></button>
主页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();
}
有人有任何想法吗?我不知道我哪弄错了!
答案 0 :(得分:1)
您应该使用以下内容作为ViewChild
参考
@ViewChild(ModalDirective) public lgModal:ModalDirective;
更新1:根据修订后的问题
您错过了infoModal
推荐,如下所示
export class HomeComponent implements OnInit {
@ViewChild(InfoModalComponent) infoModal : InfoModalComponent; ////// missing declaration
ngOnInit() {
}
showModal() {
this.infoModal.showInfoModal();
}
注意:当您使用this.infoModal
时,您需要按上述方式声明它,否则您可以在HTML中使用它们
<button class="btn-default btn pull-right next" (click)="infoModal.showInfoModal()">
Show Information
</button>
<app-info-modal #infoModal> </app-info-modal>