在 Angular 中使用 ViewChild 访问驻留在 ng-component 下的子组件

mnu*_*sir 5 ng-template viewchild angular

我有父组件,有一个ng-template部分。在这个 ng-template 部分下有一个Child Component。现在我想使用 ViewChild 装饰器访问这个子组件。使用 ViewChild 后,我想执行该子组件的功能。但它不起作用。代码如下:

<ng-template #mymodal let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">Bootstrap Modal</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <app-expense-head #child></app-expense-head>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">Ok</button>
    <button type="button" class="btn btn-outline-dark" (click)="onClickCancel()">Cancel</button>
  </div>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

TS文件代码

@ViewChild(ExpenseHeadComponent, { static: false }) childExpenseHead: ExpenseHeadComponent;

onClickCancel() {
    this.childExpenseHead.myAlert();    
  }
Run Code Online (Sandbox Code Playgroud)

Job*_*lle 1

尝试访问ngAfterViewInit() { }生命周期挂钩上的子值。