2017-10-02 9 views
0

私はangular2 + ng-bootstrap + bootstrap Beta 4で私の最初のプロジェクトを開始しています。Angular2 ng-bootstrap:同じモーダルウィンドウ用に2つの異なるボタンが必要

私の問題はこれです: 2つの異なるボタン(別のhtmlテンプレートにあります)から同じモーダルウィンドウを開きたいとします。私が見つけた唯一の解決策は、ボタンを含む私のHTMLテンプレートを複製することです。私はもっ​​と良い解決策があると確信しています。

<ng-template #contact let-c="close" let-d="dismiss"> 
    <div class="modal-header"> 
    <h4 class="modal-title">Modal1</h4> 
    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')"> 
     <span aria-hidden="true">&times;</span> 
    </button> 
    </div> 
    <div class="modal-body"> 
    <p>I'd like my 2 differents buttons to open the same modal window</p> 
    </div> 
    <div class="modal-footer"> 
    <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button> 
    </div> 
</ng-template> 

<button class="btn btn-lg btn-outline-primary" (click)="open(contact)">Contact button but with different text and style and same popup</button> 

http://plnkr.co/edit/pmRdVLyDLkJkkIPLItAL?p=preview

あなたの助けに感謝し、あなたが主成分にごcontactマークアップを移動することができます

+1

プランナーファイルが表示されません。また、あなたのコードをあなたの質問にテキストとして含めることをお勧めします。 –

+0

私は自分の投稿を編集しました。アドバイスありがとう –

答えて

0

をアドバイス。あなたの子コンポーネントで、input propertyと宣言してください。子コンポーネントで

<ngbd-modal2 [content]="contact"></ngbd-modal2> 

そして、あなたのように:

@Input() content: ElementRef; 

だから、今あなたがオプションとして子供たちに自分のマークアップを渡すことができ

open() { 
    this.modalService.open(this.content); 
} 

が更新plunkを参照してください。あなたがモーダルダイアログを呼び出しますあなたのモーダルコンテンツが定義されているコンポーネントおよびコンポーネント間で共有されるサービスを作成できるサービス

を使用して

ソリューション。このサービスでは、オブザーバブルを公開するだけで、オブザーバブルを呼び出す方法が必要です。

サービスコード:

subscription = new Subject(); 
showModal() { 
    this.subscription.next(); 
} 

ので、モーダルダイアログコンテンツを持つコンポーネントはモーダルダイアログを表示するようにsubscriptionを購読することができます:

主成分:

@ViewChild('contact') modalContent: ElementRef; 
constructor(private modalService: ModalService, private ngbModal: NgbModal) { 
    modalService.subscription.subscribe(() => { 
     this.ngbModal.open(this.modalContent) 
    }) 
} 

したがって、モーダルダイアログのコンシューマは、t彼のダイアログを表示するにはshowModal方法:

子供:

constructor(private modalService: ModalService) {} 
open() { 
    this.modalService.showModal(); 
} 

更新plunkを参照してください。

+0

ありがとう。 これは動作しますが、完全ではありません。私のセカンダリボタンは実際には "HomeComponent"にあり、モーダルウィンドウは開きません。 更新されたplunk [here](http://plnkr.co/edit/kLZMHhQKoygUudPqe29h?p = preview) –

+0

実際のコンポーネント階層を示すためにplunkを変更できますか? –

+0

申し訳ありません。私の更新版[ここ](http://plnkr.co/edit/kLZMHhQKoygUudPqe29h?p=preview) –

関連する問題