【发布时间】:2021-01-05 17:41:10
【问题描述】:
我在子组件中有mat-paginator,如下所示:
child.component.html
<mat-paginator #paginator></mat-paginator>
我想使用@ViewChild()从父组件获取这个分页器,如下所示:
parent.component.html
<child
<!-- code omitted for simplicity -->
>
</child>
***parent.component.ts***
@ViewChild('paginator') paginator: MatPaginator;
resetPaginator() {
this.paginator.firstPage();
}
但由于 this.paginator 未定义,我无法访问子组件中的分页器。我不确定如何从父级访问分页器。一种方法可能是使用以下方法,但如果有一种优雅的方法,我会更喜欢它。有什么想法吗?
@ViewChild(ChildComponent) child: ChildComponent;
【问题讨论】:
-
你应该在 AfterViewInit() 生命周期钩子上检查它
-
但我已经尝试在
AfterViewInit()之后调用的重置方法上使用它。所以,我只需要使用@ViewChild(ChildComponent) child: ChildComponent;访问子组件中的分页器的优雅方式吗?如果没有,我想我应该使用@ViewChild(ChildComponent) child: ChildComponent;来访问分页器并设置它的值。有什么想法吗? -
从父组件,您可以使用@ViewChild 访问子组件,然后您可以访问分页器
标签: javascript angular angular-material mat-table mat-pagination