我使用Angular 5.我在ngOnInit()中使用函数轮播。问题是当我点击导航到其他页面时,在控制台中显示以下消息:
TypeError: Cannot read property 'style' of undefined
at carousel (home-gr.component.ts:70)
我的组件中的代码:
ngOnInit() {
let slideIndex = 0;
function carousel() {
let i;
let x = <HTMLElement[]><any>document.getElementsByClassName("titleweb");
let y = <HTMLElement[]><any>document.getElementsByClassName("devimages");
let z = <HTMLElement[]><any>document.getElementsByClassName("devlogoimages");
let dx = <HTMLElement[]><any>document.getElementsByClassName("titlewebdes");
let dy = <HTMLElement[]><any>document.getElementsByClassName("photodesignclass");
let dz = <HTMLElement[]><any>document.getElementsByClassName("deslogoimages");
for (i = 0; i < Object.keys(x).length; i++) {
x[i].style.backgroundColor = "black";
x[i].style.color = "white";
dx[i].style.backgroundColor = "black";
dx[i].style.color = "white";
y[i].style.opacity = "0";
z[i].style.opacity = "0";
dy[i].style.opacity = "0";
dz[i].style.opacity = "0";
}
slideIndex++;
if (slideIndex > Object.keys(x).length) {slideIndex = 1}
x[slideIndex-1].style.backgroundColor = "#ff6600";
x[slideIndex-1].style.color = "black";
dx[slideIndex-1].style.backgroundColor = "#ff6600";
dx[slideIndex-1].style.color = "black";
y[slideIndex-1].style.opacity = "1";
z[slideIndex-1].style.opacity = "1";
dy[slideIndex-1].style.opacity = "1";
dz[slideIndex-1].style.opacity = "1";
setTimeout(carousel, 3000);
}
carousel();
}
也许我可以在ngOnDestroy()中破坏旋转木马功能,但我不知道如何。如果您需要更多详细信息,请让我回复。
答案 0 :(得分:1)
调用clearTimeout()取消ngOnDestroy
上的setTimeout实例。
private carouselTimeoutVar : any;
ngOnInit() {
this.carouselTimeoutVar = setTimeout(carousel, 3000);
}
ngOnDestroy() {
clearTimeout(this.carouselTimeoutVar);
}