【问题标题】:The same data is displayed differently in angular9.why?相同的数据在 angular9 中显示不同。为什么?
【发布时间】:2020-08-24 04:45:27
【问题描述】:

在下面的例子中,

  • 第一个表达式{{ bar }} 永远不会更新,但是
  • 第二个表达式{{ "" + bar }} 已更新:

例如

two
1588950994873

为什么会这样?

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  template: `
    What is different and why?
    <br />
    {{ bar }} <br />
    {{ "" + bar }} <br />
  `
})
export class AppComponent {
  value: string = "default";

  bar: any = d => {
    this.value = d;
  };

  ngOnInit() {
    this.bar.valueOf = () => this.value;
    this.bar("one");
    setInterval(() => this.bar(Date.now() + ""), 1000);
    this.bar("two");
  }
}

Stackblitz example

【问题讨论】:

  • 只是一个理论(对这种行为没有任何启发):当它只需要取消引用一个变量并且必须计算它将显示在花括号内的值时,Angular 处理不同的简单表达式.

标签: angular typescript asynchronous angular9 zonejs


【解决方案1】:

原因是角度变化检测通过比较表达式的实例来工作:

  • {{ bar }}:实例bar 永远不会改变——你为这个类成员分配了一个函数并且你永远不会重新分配它——所以每个变化检测周期都会看到bar 仍然是同一个实例并且不会更新它(即因为实例相同,我们甚至不要求值)
  • {{ "" + bar }}:在每个更改检测周期中,都会评估表达式 "" + bar。评估此字符串连接时,我们必须获取bar,该值将由您的计时器更新。因此字符串连接的结果将始终是一个新的字符串实例,因此更改检测将更新视图。

【讨论】:

  • 为什么 {{bar}} 是 'two' ,而不是 'one' 或 'default'?
  • ngOnInit 完成之前视图不会更新 - 所以最后一个分配“获胜”。检查life-cycle docs
猜你喜欢
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
相关资源
最近更新 更多