2016-11-07 12 views
0

私はng2-bootstrapとモーダルコンポーネントを使用します。しかし、質問はng2-bootstrapに関するものではありません。私は私のrootコンポーネントに次のテンプレートを持っている:角度2.子ビューへのアクセス

... for brevity 
<div bsModal #lgModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="modalLabel" 
    aria-hidden="true"> 
    <div class="modal-dialog modal-md"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" (click)="lgModal.hide()" aria-label="Close"> 
        <span aria-hidden="true">&times;</span> 
       </button> 
       <h4 class="modal-title">Header</h4> 
      </div> 

      <div class="modal-body"> 
       <p>Modal body</p> 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default">Save</button> 
      </div> 
     </div> 
    </div> 
</div> 

私はコンポーネントでlgModalを取得したいです。だから、私は持っているコンポーネントで:

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

すべてがうまくいきます。しかし、私は別のコンポーネントにモーダルHTMLを入れたいと思っています。たとえば、app-modalです。その後、私が持っているrootコンポーネントで:

...for brevity 
<app-modal></app-modal> 

しかし、この場合には、lgModalrootコンポーネントで定義されていません。どのように適切にそれを取得するには?あなたの親コンポーネントで

答えて

1

は次のように子コンポーネントを定義する:子コンポーネントへ

@ViewChild(AppModalComponent) appModalComponent: AppModalComponent; //assuming the name of the child component is AppModalComponent 

移動

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

。 は、次に、あなたの親コンポーネントに

this.appModalComponent.lgModal = "something"; 

で、子コンポーネントであるlgModalプロパティにアクセスすることができます。

Ref:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-calls-a-viewchild-

+1

Cool。答えをありがとう。 – user348173

関連する問題