场景
我正在尝试创建自定义的打字效果Like this,其角度延迟为100毫秒。
下面是我的打字稿代码:
private arr: string[] = ["Lead Developer (.NET)", "Full Stack (.NET) Developer", "Freelancer"];
private typewriter_text: string = "";
private typewriter_display: string = "";
ngOnInit() {
this.typingInitiating(this);
}
typingInitiating(that) {
this.arr.forEach(element => {
that.typewriter_text = element;
this.typingCallback(that);
});
}
typingCallback(that) {
if (this.typewriter_display.length < that.typewriter_text.length) {
this.typewriter_display += that.typewriter_text[this.typewriter_display.length];
setTimeout(that.typingCallback, 100, that);
}
else {
for (let i = that.typewriter_text.length; i >= 0; --i) {
this.typewriter_display = that.replaceAt(that.typewriter_text, i,that.typewriter_text.length - i);
console.log(this.typewriter_display)
}
}
}
replaceAt(text: string, index: number, charcount: number): string {
return text.substr(0, index) + text.substr(index + charcount);
}
在我的App.Component.html中:
{{typewriter_display }}
Live Stackblitz
我在控制台中遇到错误:
https://stackblitz.com/edit/angular-rqtvoz
我想知道为什么我的递归无法正常工作。
答案 0 :(得分:0)
this
在函数中丢失,并且不引用对象本身。创建的每个函数都有自己的this
。我们将需要将其更改为箭头功能,因为它不绑定它自己的
typingCallback = (that:any) => {
if (this.typewriter_display.length < that.typewriter_text.length) {
this.typewriter_display +=
that.typewriter_text[this.typewriter_display.length];
setTimeout(that.typingCallback, 100, that);
}
else {
for (let i = that.typewriter_text.length; i >= 0; --i) {
this.typewriter_display = that.replaceAt(that.typewriter_text,
i,that.typewriter_text.length - i);
console.log(this.typewriter_display)
}
}
};