gpt4 book ai didi

javascript - Angular 如何从父组件访问子组件?

转载 作者:行者123 更新时间:2023-12-02 16:20:41 25 4
gpt4 key购买 nike

我在子组件中有 mat-paginator,如下所示:


child.component.html

<mat-paginator #paginator></mat-paginator>

我想使用 @ViewChild() 从父组件获取分页器,如下所示:


parent.component.html

<child 
<!-- code omitted for simplicity -->
>
</child>

***父组件.ts***
@ViewChild('paginator') paginator: MatPaginator;

resetPaginator() {
this.paginator.firstPage();
}

但由于 this.paginator 未定义,我无法在子组件中访问分页器。我不确定如何从父级访问分页器。一种方法可能使用以下方法,但如果有一种优雅的方法,我会更喜欢它。有什么想法吗?

@ViewChild(ChildComponent) child: ChildComponent;

最佳答案

Friedrick, parent 只能访问“ child ”(但如果可以访问 child ,则可以访问 child 的所有属性和功能)。所以在你的 child 中你声明

//in CHILD, so this variable can be access from parent
@ViewChild('paginator') paginator: MatPaginator;

在 parent 中你有一个

@ViewChild('child') child: ChildComponent;

你像往常一样得到“ child 的分页器”

this.child.paginator.firstPage();

请注意,您还可以向子项添加模板引用并避免声明 viewChild

<child-component #child..></child-component>
<button (click)="child.paginatorfirstPage()">first</button>
<button (click)="doSomething(child)">something</button>
doSomething(child:any)
{
child.paginator.lastPage()
}

关于javascript - Angular 如何从父组件访问子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65574814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com