首页 > 解决方案 > 当变量更改时,h2 插值不会更新

问题描述

当变量更改时,h2 插值不会更新我想要做的是将字母添加到 displayWord 变量 看起来好像输入了单词 TS

  displayedWord = ''
  words = ['Innovation', 'Inspiration']


  changeWord = (words) => {

    const wordArray = this.words[0].split('')
    const lettersToDisplay = []

    for (let i = 0; i < wordArray.length; i++) {
      setTimeout(function () {
        const letter = wordArray[i];
        lettersToDisplay.push(letter)
        this.displayedWord = lettersToDisplay.join('');
        console.log(this.displayedWord);
      }, 1000 * i);
    }
  }


  ngOnInit(): void {
    this.changeWord(this.words);
  }

HTML

        <h2 class="about__title">We help you discover the power of {{displayedWord}}_

标签: angulartypescript

解决方案


你必须改变:

setTimeout(function() { ... } )

至:

setTimeout(() => {...})

为了this引用组件实例。

看看这里

指出:

没有自己的绑定到this.

函数表达式相比


推荐阅读