簡體   English   中英

angular:使用間隔生成的值未使用 {{}} 在瀏覽器中反映

[英]angular: value generated using interval not reflecting in browser using {{}}

我試圖在 web 頁面中顯示每秒更改的值,但 {{}} 不起作用。 但是,我使用了 console.log,它確實顯示了變化的值。

這是 my.ts 代碼片段

randomValue: number;
processIncrementValue(){    
this.randomValue = Math.floor((Math.random()*100)+1);
console.log("generating random number: " + this.randomValue);
}
// on this function by button press, value starts to change
start(){
console.log("generating random number: start " + this.randomValue);
this.myVar = setInterval(this.processIncrementValue, 1000);
}

.HTML 文件片段

<div class="row">
<button type="button" class="btn btn-primary" (click)="start()">Start</button>
<hr>
<div class="row">
<p>my name is: {{randomValue}}</p>
</div>
</div>

使用 ES6 箭頭 function () =>將 setInterval 綁定到 scope

this.myVar = setInterval(()=>{this.processIncrementValue()}, 1000);

當你使用setInterval(function () { doThing() }); ,它將this綁定到window object。 所以在 function doThing()如果你有this.doSomething ,你的代碼想要在window object 中找到一個變量doSomething存在。

當您使用箭頭 function 時,它會將其綁定到this scope,這是您的 angular 組件。


來自: https://www.w3schools.com/js/js_arrow_function.asp

在常規函數中, this關鍵字代表 object,稱為 function,它可以是 window、文檔、按鈕或其他。

對於箭頭函數, this關鍵字始終表示定義箭頭 function 的 object

你可以試試這個

.TS 文件

 randomValue: number; // = 0 if you need to initialize it processIncrementValue() { this.randomValue = Math.floor((Math.random() * 100) + 1); setTimeout(() => { this.processIncrementValue(); }, 1000); }

.HTML 文件

<div class="row">
  <button type="button" class="btn btn-primary" (click)="processIncrementValue()">Start</button>
  <div class="row">
    <p>my name is: {{randomValue}}</p>
  </div>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM