@ViewChild始终返回未定义 [英] @ViewChild always returns undefined
问题描述
我知道之前已经有人问过这个问题,但是没有一个答案对我有用.
I know this has been asked before, but none of the selected answers are working for me.
我正在尝试使用@ViewChild从dom获取我的ng-select.并且总是返回undefined
I am trying to use @ViewChild to get my ng-select from the dom. And it always returns undefined
这是main.html中的选择
here is the select inside the main.html
<ng-select id="user-select"
#userSelect
[allowClear]="true"
[items]="singleSignOnUsers"
[disabled]="disabled"
placeholder="No user selected">
</ng-select>
这是我的组件
import { Component, AfterViewInit, ViewChild } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app-main',
templateUrl: '../app/main.html',
providers: [ApiHttpService, UserAdministrationService]
})
export class AppComponent {
@ViewChild('userSelect') userSelect;
ngAfterViewInit() {
alert(this.userSelect);
}
}
我在这里想念什么?
更新:哦,我的灵魂! 我弄清楚了为什么在这种情况下它不起作用. 我用ngSwitch将整个视图包装在div中.如果我将其移出...我可以访问它们.现在,我不知道如何在ngSwitch中访问它们.但是我不必使用ngSwitch
Update: Oh My Soul! I figured out why this wasn't working when this should.. I have the whole view wrapped in a div with an ngSwitch. If i move it out... I can access them. Now I don't know how to access them while in the ngSwitch however. But I can don't have to use the ngSwitch
<div [ngSwitch]='loading'>
<div *ngSwitchCase="false">
...
<ng-select id="user-select"
#userSelect
[allowClear]="true"
[items]="singleSignOnUsers"
[disabled]="disabled"
placeholder="No city selected">
</ng-select>
...
</div>
<div
推荐答案
@twaldron您是否正在ngOnInit中使用某些延迟的数据加载?
@twaldron Are you using some delayed data loading in ngOnInit?
因为在这种情况下,以我的经验,将@ViewChild读取为ElementRef不会产生结果
Because in that case, in my experience, reading a @ViewChild as a ElementRef produces no results
如果您的组件中的数据已经解析(例如父级将子数据对象传递给子组件的情况),则它应该可以工作(至少对我而言是如此).
If your component has the data already resolved (like the case when a parent passes a child data object to a sub component) it should work (at least for me it did).
在异步数据加载的情况下,我能够使其工作的方法是使用更改通知
In the case of asynchronous data loading, the way I was able to make it work is using a change notification
@ViewChildren('userSelect') userSelect: QueryList<ElementRef>;
ngAfterViewInit(): void {
this.userSelect.changes.subscribe(item => {
if (this.userSelect.length) {
alert(this.userSelect.first.nativeElment.outerHTML)
}
})
}
这篇关于@ViewChild始终返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!