如何从Angular的父组件访问子组件?

问题描述

我在子组件 a 中有 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,父级只能访问“子级”(但如果可以访问子级,则可以访问子级的所有属性和功能)。所以在你的孩子中你声明

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

在父母中你有一个

@ViewChild('child') child: ChildComponent;

你会像往常一样得到“孩子的分页器”

this.child.paginator.firstPage();

注意,你也可以给child添加模板引用,避免声明viewChild

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

静态查询迁移指南 给图书馆作者的重要说明:这种迁移对于图书馆作者来说尤其重要,可以帮助他们的用户在版本 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 开始,静态标志将默认为 false。届时,任何 {static: false} 标志都可以安全地移除,我们将有一个原理图为您更新您的代码。

注意:此标志仅适用于@ViewChild 和@ContentChild 查询,因为@ViewChildren 和@ContentChildren 查询没有静态和动态的概念(它们总是被解析为“动态”)。>

Static query migration guide