2016-11-07 100 views
0

我使用ng2-bootstrap和模态组件。但是,问题不在于ng2-bootstrap。我有以下的模板在我root组件:Angular 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; 

所有的工作正常。但是,我想把modal 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

很酷。感谢你的回答。 – user348173