[英]ViewChild reference of searchBar suddenly undefined when moving to child component
Good afternoon!下午好! I implemented a searchbar like described in https://www.chriswoolum.dev/using-ion-searchbar-to-filter-an-observable-collection for my Angular + Ionic app.
我为我的 Angular + Ionic 应用程序实现了一个类似于https://www.chriswoolum.dev/using-ion-searchbar-to-filter-an-observable-collection 中描述的搜索栏。
After moving it to a own component, suddenly the searchBar is undefined, even in the ngAfterViewInit() where it should have been initialized already.将其移动到自己的组件后,突然之间 searchBar 未定义,即使在它应该已经初始化的 ngAfterViewInit() 中也是如此。
my-list.component.ts 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 my-list.component.html
<ion-searchbar #searchBar placeholder="Search.."></ion-searchbar>
Does anyone have an idea or can explain to me how the lifecycle is for component as somehow it is handled differently than directly using it in a page.有没有人有想法或可以向我解释组件的生命周期如何,因为它的处理方式与直接在页面中使用不同。
Kind regards亲切的问候
If you use @ViewChild()
with {static : true}
it basically means you expect that component to be present as soon as the page loads, therefore the @Viewchild()
query will not update on every digest cycle.如果您将
@ViewChild()
与{static : true}
则基本上意味着您希望该组件在页面加载后立即出现,因此@Viewchild()
查询不会在每个摘要周期更新。
In simple terms, this means that if your component is displayed based on an ngIf, {static : true}
will not pick it up .简单来说,这意味着如果您的组件是基于 ngIf 显示的,则
{static : true}
将不会选择它。
For the sake of the argument i'm gonna assume your为了争论,我假设你
<ion-searchbar #searchBar placeholder="Search.."></ion-searchbar>
Is wrapped by an *ngIf at a higher level被更高级别的 *ngIf 包裹
Try to change your code with尝试更改您的代码
@ViewChild(IonSearchbar, {static: false}) searchBar: IonSearchbar;
@ViewChild(IonSelect, {static: false}) selectBodypart: IonSelect;
you should then see your component然后你应该看到你的组件
If that also does not work try to reference your component directly like so:如果这也不起作用,请尝试直接引用您的组件,如下所示:
@ViewChild("searchBar", {static: false}) searchBar: IonSearchbar;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.