在ngOnInit()mehtod中,我得到一个HTMLElement并用它来设置一个变量:
ngOnInit(){
this.popUpContainerDisplay = document.getElementById('popUpContainer');
console.log("pop", this.popUpContainerDisplay);
this.popUpAcceptContainerDisplay = document.getElementById('acceptPopUp');
this.popUpDeclineContainerDisplay = document.getElementById('declinePopUp');
this.popUpWarningContainerDisplay = document.getElementById('warningPopUp');
}
popUpFadeOut(): void{
if(this.popUpContainerDisplay.style.opacity == "0"){
console.log("fine", this.popUpContainerDisplay);
this.popUpContainerDisplay.style.opacity = "1";
this.popUpContainerDisplay.style.display = "block";
setTimeout(this.fade, 1000); //popup box fades away after 1 seconds
}
}
fade(): void {
console.log("notFine", this.popUpContainerDisplay);
this.newOpacity = parseInt(this.popUpContainerDisplay.style.opacity) - .01;
this.popUpContainerDisplay.style.opacity = String(this.newOpacity);
if (this.newOpacity <= 0)
{
this.popUpContainerDisplay.style.display = "none";
this.popUpContainerDisplay.style.opacity = "0";
}
else
{
requestAnimationFrame(this.fade);
}
}
constructor(private biddingService: BiddingService) {
biddingService.bids.subscribe(bid => {
if(bid.bidderArray){
this.bidderArray = bid.bidderArray; //.join('');
this.highestBid = bid.bid;
this.popUpContainerDisplay.style.display = bid.popUpContainerDisplay;
this.popUpContainerDisplay.style.opacity = bid.popUpContainerOpacity;
this.popUpAcceptContainerDisplay = bid.popUpAcceptContainerDisplay;
this.popUpDeclineContainerDisplay = bid.popUpDeclineContainerDisplay;
this.popUpWarningContainerDisplay = bid.popUpWarningContainerDisplay;
this.arrayReset = bid.resetArrayBoolean;
this.popUpFadeOut();
}
});
}
ngOnInit()和popUpFadeOut()在控制台中记录元素,但fade()记录'undefined'。为什么元素突然未定义?
答案 0 :(得分:0)
您可以使用箭头功能确保this
方法中的上下文fade
成为您组件的实例:
setTimeout(() => this.fade(), 1000);
或
fade = () => {
console.log("notFine", this.popUpContainerDisplay);
this.newOpacity = parseInt(this.popUpContainerDisplay.style.opacity) - .01;
另请参阅此处的其他选项: