@ViewChild未定义 [英] @ViewChild is undefined
问题描述
我试图用 * ngIf
切换 @ViewChild
元素,然后在此之后,调用本地事件.
I am trying to toggle a @ViewChild
element with an *ngIf
and then after this, call a native event.
这是我的html元素,装饰有 #audioPlayer
,因此我可以通过 @ViewChild
提取元素.
This is my html element, adorned with #audioPlayer
so I can extract the element via @ViewChild
.
<audio
#audioPlayer
*ngIf="conversationIsRunning"
[src]='activeConversation?.clips[activeConversation.activeClipId].audio.blob'
(ended)="audioComplete($event)"
autoplay controls preload="auto" >
</audio>
在我的打字稿中,我有以下内容:
In my typescript I have the following:
@ViewChild('audioPlayer') audioPlayer;
private conversationIsRunning: boolean;
ngOnInit() {
this.conversationIsRunning = false;
}
ngOnChanges() {
console.log("ngOnChanges");
this.conversationIsRunning = true;
console.log(this.audioPlayer); // undefined
this.audioPlayer.nativeElement.play(); // error
}
如果我从 audio
元素中删除了 * ngIf
,该错误就会消失.但是,我确实希望将这种功能放在适当的位置,以便在不需要时可以销毁该元素.
The error disappears if I remove the *ngIf
from the audio
element. However I really want this functionality in place where the element is destroyed when I don't need it.
我在此答案中看到,您可以在上使用setter@ViewChild
,所以我实现了,但是没有成功...
I saw in this answer that you can use a setter on @ViewChild
so I implemented that, however to no success...
private privAudioPlayer: ViewContainerRef;
@ViewChild('audioPlayer') set audioPlayer(audioPlayer: ViewContainerRef) {
this.privAudioPlayer = audioPlayer;
console.log('audioPlayer set called >> ', audioPlayer, this.privAudioPlayer);
};
...但是,这始终会输出称为>>的 audioPlayer集.未定义未定义
...however this always outputs audioPlayer set called >> undefined undefined
我还尝试将 this.conversationIsRunning = true;
从其当前位置拆分,并放入各种不同的ng生命周期挂钩,然后还将 ngOnChanges
更改为其他生命周期挂钩也无济于事.
I have also tried splitting the this.conversationIsRunning = true;
from its current location and putting into a variety of different ng lifecycle hooks, and then also changing ngOnChanges
to other lifecycle hooks as well to no avail.
我是否必须等到下一帧或其他内容?为什么 set audioPlayer
增变器会收到 undefined
?
Do I have to wait until next frame or something? And why does that set audioPlayer
mutator recieve undefined
?
推荐答案
在第一个代码示例中,应使用 ngAfterViewInit()
而不是 ngOnChanges()
.
In the first code example, you should use ngAfterViewInit()
instead of ngOnChanges()
.
这篇关于@ViewChild未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!