簡體   English   中英

移動到子組件時,searchBar 的 ViewChild 引用突然未定義

[英]ViewChild reference of searchBar suddenly undefined when moving to child component

下午好! 我為我的 Angular + Ionic 應用程序實現了一個類似於https://www.chriswoolum.dev/using-ion-searchbar-to-filter-an-observable-collection 中描述的搜索欄。

將其移動到自己的組件后,突然之間 searchBar 未定義,即使在它應該已經初始化的 ngAfterViewInit() 中也是如此。

my-list.component.ts

  @ViewChild(IonSearchbar, {static: true}) searchBar: IonSearchbar;
  @ViewChild(IonSelect, {static: true}) selectBodypart: IonSelect;


  ngAfterViewInit() {
    console.log(this.searchBar) # undefined
  }

my-list.component.html

  <ion-searchbar #searchBar placeholder="Search.."></ion-searchbar>

有沒有人有想法或可以向我解釋組件的生命周期如何,因為它的處理方式與直接在頁面中使用不同。

親切的問候

如果您將@ViewChild(){static : true}則基本上意味着您希望該組件在頁面加載后立即出現,因此@Viewchild()查詢不會在每個摘要周期更新。

簡單來說,這意味着如果您的組件是基於 ngIf 顯示的,則{static : true}將不會選擇它

為了爭論,我假設你

<ion-searchbar #searchBar placeholder="Search.."></ion-searchbar>

被更高級別的 *ngIf 包裹

嘗試更改您的代碼

@ViewChild(IonSearchbar, {static: false}) searchBar: IonSearchbar;
@ViewChild(IonSelect, {static: false}) selectBodypart: IonSelect;

然后你應該看到你的組件

如果這也不起作用,請嘗試直接引用您的組件,如下所示:

@ViewChild("searchBar", {static: false}) searchBar: IonSearchbar;

暫無
暫無

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

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