Angular 调用嵌套组件中的方法

Angular 调用嵌套组件中的方法,angular,viewchild,Angular,Viewchild,我有两个组件(1-应用程序学生列表2-应用程序学生详细信息) 我想在学生列表中使用学生详细信息,如下所示: app-student-detail.html <p>Student Detail Component is here ....</p> app-student-list.html <p>Student List Component is here ....</p> <app-student-detail></app-st

我有两个组件(1-应用程序学生列表2-应用程序学生详细信息

我想在
学生列表中使用
学生详细信息
,如下所示:

app-student-detail.html

<p>Student Detail Component is here ....</p>
app-student-list.html

<p>Student List Component is here ....</p>
<app-student-detail></app-student-detail>
showdeail
方法中,我想调用名为
showdeail

最后,我想在AppComponent中使用学生列表

app.component.ts

export class AppComponent {
  public isShow = false;

  @ViewChild(StudentListComponent, { static: true }) studentList: StudentListComponent;
  title = 'AngualrViewChild';

  showDetail() {
    this.isShow = true;
    this.studentList.showDetail();
  }

}
app.component.html

<p>App Component is here ....</p>
<app-student-list *ngIf="this.isShow"></app-student-list>

<hr />
<button type="button" (click)="this.showDetail()">
    Show Detail
</button>
注意:当我删除上面的
ngIf
时,它会很好地工作


如果未显示学生列表(您的*ngIf计算结果为false),则您的学生列表也不会在任何地方呈现/可用

因此,ViewChild无法解析任何内容,调用“this.studentList.showdeail();”将无法工作。是的,您已将布尔值更改为true,但changeDetection可能没有足够的时间运行并实际呈现学生列表

在你的App.Component中,你还应该重新考虑你的:

{ static: true }
您的viewchild目前远不是静态的,因为它依赖于*ngIf来解析。将其设置为“static:true”将阻止ViewChild在学生列表实际可用时进行更新

你有两个选择

  • (肮脏的解决方法)将布尔值切换为true,允许*ngIf执行正确的更改(显示学生列表),然后调用showDetails方法,如下所示:
  • (cleaner)如果希望在StudentList可用时立即调用函数,可以在StudentList.component中实现并调用函数
  • 例如:

    import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
    

    这两个函数都应该给出您期望的结果,但是在从父组件调用子组件函数之前,请考虑一下为什么要这样做

    你真的希望父母触发对孩子的动作,还是希望孩子在达到某个生命周期后做些什么?大多数情况下,逻辑可以在子组件中实现,父组件只关心渲染或隐藏子组件

    AppComponent.html:6 ERROR TypeError: Cannot read property 'showDetail' of undefined
    
    { static: true }
    
    import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';