【问题标题】:Call a method in the nested component在嵌套组件中调用方法
【发布时间】:2019-12-02 08:31:07
【问题描述】:

我有两个组件(1-app-student-list 2-app-student-detail)。

我想在student-list 中使用student-detail,如下所示:

app-student-detail.html

<p>Student Detail Component is here ....</p>

app-student-detail.ts

export class StudentDetailComponent {
  showDetail() {
    alert("We are in student-detail...");
  }
}

app-student-list.html

<p>Student List Component is here ....</p>
<app-student-detail></app-student-detail>

app-student-list.ts

export class StudentListComponent implements OnInit {

  @ViewChild(StudentDetailComponent, { static: true }) studentDetail: StudentDetailComponent;
  constructor() { }

  ngOnInit() {
  }

  showDetail() {
    this.studentDetail.showDetail();
  }

}

showDetail方法中我想调用一个名为StudentDetailComponent的方法showDetail

最后,我想在 AppComponent 中使用 student-list

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>

当我调用StudentListComponentshowDetail 方法时,出现以下错误:

AppComponent.html:6 ERROR TypeError: Cannot read property 'showDetail' of undefined

注意:当我删除上面的ngIf 时,它会正常工作

Stackblitz is here

【问题讨论】:

    标签: angular viewchild


    【解决方案1】:

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

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

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

    { static: true }
    

    目前,您的 viewchild 远非静态,因为它依赖于 *ngIf 来解决。将其设置为 "static: true" 将阻止您的 ViewChild 在您的 StudentList 实际可用时更新。

    More info about this property.

    这里有两个选择。

    1. (肮脏的解决方法)将您的布尔值切换为 true,让您​​的 *ngIf 执行正确的更改(显示您的 StudentList),然后像这样调用您的 showDetails 方法:

    1. (更简洁)如果您希望在 StudentList 可用时立即调用函数,您可以在 StudentList.component 中实现 AfterViewInit() 并调用您的函数。

    例如:

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

    两者都应该为您提供您期望的结果,但在从父组件调用子组件函数之前,请考虑您为什么要这样做。

    您真的希望父母触发对孩子的动作,还是希望孩子在他达到某个生命周期后做某事?大多数时候,逻辑可以在子组件中实现,而您的父组件只关心渲染或隐藏子组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-29
      • 2013-01-03
      • 2015-09-15
      相关资源
      最近更新 更多