Angular 如何使用事件从父组件触发子函数

Angular 如何使用事件从父组件触发子函数,angular,viewchild,Angular,Viewchild,我在父html中有一个单击事件函数 <span (click)="onFilterClick()" class="filter-icon"> <mat-icon>keyboard_arrow_down</mat-icon></span> <m-scp-filter-template [openFilter]="true" *ngIf="templateFor === 'col1' "></m-scp-filter-template

我在父html中有一个单击事件函数

<span (click)="onFilterClick()" class="filter-icon">
<mat-icon>keyboard_arrow_down</mat-icon></span>
<m-scp-filter-template [openFilter]="true" *ngIf="templateFor === 'col1' "></m-scp-filter-template>
父ts上的函数

@ViewChild(ScpFilterTemplateComponent) myChild;
onFilterClick() {
  this.myChild.openMenu();
}
并在子ts处调用函数

openMenu() {
     console.log('successfully executed.');
}
但我发现了一个错误

'TypeError:无法读取未定义的属性'openMenu' 在ScpDataTableComponent上。”


这是一份来自Angular文档的副本

在本例中,当单击父组件的按钮时,start和stop方法调用子组件的相应方法

如果子组件上设置了*ngIf,则可以通过

你能试一下二传手吗

@ViewChild(ScpFilterTemplateComponent) 
set _myChild(v) {
  setTimeout(() => { this.myChild= v; }, 0);
}
或者包装this.myChild.openMenu;在超时时间内等

由于@ViewChild引用了现有的子视图/选择器,因此子视图需要存在于父HTML中。如果*ngIf返回false,Angular甚至不会在父HTML中创建子视图。因此,在这种情况下,myChild本身将是未定义的&您将无法进一步访问任何方法/属性。 还有一种替代方法——您可以创建子类的实例并调用该方法,但不建议这样做。
这是两个场景的最小复制。

可能重复@TusharWalzade,我不想使用ngAfterViewInit。只需单击触发按钮,即可尝试使用@ViewChildScpFilterTemplateComponent类型更新属性myChild:ScpFilterTemplateComponent;组件是否可见?因为您使用的是*ngIf,它可能会从域中删除。您的模板中有ngIf,您确定scpfiltertemplateComponents可见吗?谢谢,我正在寻找事件触发函数。这不是同一个问题。ngIf可能会导致演示中缺少的问题,因此OP可能需要包装此.myChild.openMenu;在超时时间内等。
@ViewChild(ScpFilterTemplateComponent) 
set _myChild(v) {
  setTimeout(() => { this.myChild= v; }, 0);
}