簡體   English   中英

如何從 Angular 中的父組件訪問子組件?

[英]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>

***parent.component.ts***
 @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 和動態的概念(它們總是被解析為“動態”)。

Static 查詢遷移指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM