[英]How to access child component from parent component in Angular?
我在子组件中有mat-paginator
,如下所示:
child.component.html
<mat-paginator #paginator></mat-paginator>
我想使用@ViewChild()
从父组件获取这个分页器,如下所示:
父组件.html
<child
<!-- code omitted for simplicity -->
>
</child>
@ViewChild('paginator') paginator: MatPaginator; resetPaginator() { this.paginator.firstPage(); }
但由于this.paginator
未定义,我无法访问子组件中的分页器。 我不确定如何从父级访问分页器。 一种方法可能是使用以下方法,但如果有一种优雅的方法,我会更喜欢它。 任何想法?
@ViewChild(ChildComponent) child: ChildComponent;
Friedrick,父级只能访问“子级”(但如果可以访问子级,则可以访问子级的所有属性和 function)。 所以在你的孩子身上你声明
//in CHILD, so this variable can be access from parent
@ViewChild('paginator') paginator: MatPaginator;
在父母中,您有一个
@ViewChild('child') child: ChildComponent;
你像往常一样得到“孩子的分页器”
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()
}
Static 查询迁移指南库作者的重要说明:此迁移对于库作者来说尤其重要,以方便他们的用户在版本 9 可用时升级。
在版本 9 中,@ViewChild 和 @ContentChild 查询的默认设置正在更改,以修复查询中的错误和令人惊讶的行为(在此处阅读更多信息)。
为了准备此更改,在版本 8 中,我们正在迁移所有应用程序和库,以明确指定 @ViewChild 和 @ContentChild 查询的解析策略。
具体来说,此迁移添加了一个明确的“静态”标志,该标志指示何时应分配该查询的结果。 添加此标志将确保您的代码在升级到版本 9 时以相同的方式工作。
前:
// query results sometimes available in `ngOnInit`, sometimes in `ngAfterViewInit` (based on template)
@ViewChild('foo') foo: ElementRef;
后:
// query results available in ngOnInit
@ViewChild('foo', {static: true}) foo: ElementRef;
或者
// query results available in ngAfterViewInit
@ViewChild('foo', {static: false}) foo: ElementRef;
从版本 9 开始,static 标志将默认为 false。 届时,任何 {static: false} 标志都可以安全地删除,我们将提供一个示意图,为您更新代码。
注意:此标志仅适用于 @ViewChild 和 @ContentChild 查询,因为 @ViewChildren 和 @ContentChildren 查询没有 static 和动态的概念(它们总是被解析为“动态”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.