2016-09-20 34 views
2

我試圖從父組件打開ng2-bootstrap模態。我創建了一個ModalComponent,並且我「exportAs:child」。我ModalComponent看起來像angular2:從父組件打開ng2-bootstrap模態

import { Component, Input, ViewChild } from '@angular/core'; 
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap'; 

@Component({ 
    selector: 'modal', 
    moduleId: module.id, 
    templateUrl: 'modal.component.html', 
    styleUrls: ['modal.component.css'], 
    exportAs: 'child' 
}) 
export class ModalComponent { 

    @ViewChild('childModal') public childModal:ModalDirective; 

    public show(variant):void { 

     console.log(this.childModal); 
     this.childModal.show(); 
    } 

    public hide():void { 

     this.childModal.hide(); 
    } 
} 

,我包括父模板的模式爲

<modal #c="child"></modal> 

...從父模板稱其爲

<button type="button" class="btn btn-primary" (click)="c.show(variant)">open</button> 

我打的「在ModalComponent中正確顯示「方法」,但「childModal」的值始終未定義(Nb:console.log()語句)。

任何指針,非常感謝。

+0

你可以發佈你的'modal.component.html'文件嗎?並檢查這個plunker https://plnkr.co/edit/951NyF20qXudDtZo5OAx?p=preview – yurzui

+0

謝謝!我經歷了你的闖入者,發現我懷疑你的錯誤在HTML中。我將在下面寫出解決方案。 – prime

+0

@yurzui只是注意到,截至今天,plunker並沒有工作,顯然是由於* ng2-bootstrap *從其

2

在我看來,需要你瀏覽組件和查詢模態實例的模態API還不是最優的。更好的方法是將模態作爲服務。這樣,您可以從代碼的任何位置(包括服務,例如:登錄服務)調用open方法。

這正是爲什麼在https://ng-bootstrap.github.io/#/components/modal中將模塊的API建模爲服務的原因。通過使用它,您可以通過簡單地執行modalService.open(....)來調用任何地方的模式。在其他Angular2構件庫(例如材料設計)中也存在基於服務的模態方法。

簡而言之:重新考慮您正在使用的API。

+0

完全同意。我正在考慮使用ng2-bootstrap,但它讓我感到困惑,因爲它違背了大多數其他庫提供模式服務的方式。 – GFoley83