【问题标题】:How is *ngfor works in this example*ngfor 在这个例子中是如何工作的
【发布时间】:2021-10-14 01:38:24
【问题描述】:

我不明白*ngfor 在这个例子中如何每次都运行并且只输出最后一个附加值,谁能给我解释一下? 如果每次数组Numberssetinterval 函数中更新,并且每次都会触发 ngfor,不应该每 1000 毫秒输出整个数组吗? 就像:
数字是 - 0
数字是 - 0
数字是 - 1
数字是 - 0
数字是 - 1
数字是 - 2
...

结果是这样的:
数字是 - 0
数字是 - 1
数字是 - 2
数字是 - 3
...

这里是应用根组件 TS

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  interval = 0;
  lastNumber = 0;

  Numbers:number[] = [];

  TimeTick()
  {
    this.interval = setInterval(() =>
    {
      this.Numbers.push(this.lastNumber);
      this.lastNumber++;
    }, 1000)
  }
}

这是应用程序根组件 HTML

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <button class="btn btn-primary" (click)="TimeTick()">Start</button>
      <app-loop-x *ngFor="let num of Numbers" [number]="num"></app-loop-x>
    </div>
  </div>
</div>

这里是 app-loop-x TS

import {Component, Input} from '@angular/core';

@Component({
  selector: 'app-loop-x',
  templateUrl: './loop-x.component.html',
  styleUrls: ['./loop-x.component.css']
})

export class LoopXComponent {

  @Input() number: number = 0;
}

这是 app-loop-x HTML

<p>Number is - {{ number }}</p>

【问题讨论】:

    标签: angular ngfor angular2-directives


    【解决方案1】:

    你不应该这样:

    数字是 - 0 数字是 - 0 数字是 - 1 数字是 - 0 数字是 - 1 数字是 - 2

    因为每一秒你都在推最后一个数字的值,然后你做 + 1 到最小数字(推后)

    所以在 1 秒后你按下 0 并且你在 lastNumber 处 +1 所以下一秒你将按下 1 然后下一秒 2 ....

    这是对那些台词的解释

        this.interval = setInterval(() =>
        {
          this.Numbers.push(this.lastNumber);
          this.lastNumber++;
        }, 1000)
    

    【讨论】:

    • 顺便说一下 ngFor 是由角度计时器触发的(当角度检测到变化或类似的事情时......)并且 ngFor 不仅显示最后一个,而是显示数组的所有元素。 (它遍历数组以获取每个数据,然后您决定将它们显示到 html 中)
    【解决方案2】:

    当您更改数组 Numbers 的值时,*ngFor 指令会更新输出,它不会为每次更改创建新的输出。

    变更传播 当迭代器的内容发生变化时,NgForOf 会对 DOM 进行相应的更改:

    添加项目时,模板的新实例会添加到 DOM。

    当一个项目被移除时,它的模板实例就会从 DOM 中移除。

    当项目重新排序时,它们各自的模板在 DOM 中重新排序。

    所以“最后一个值”不再存在,因为它已被新值覆盖。

    一般来说,如果您有一个数组文本,例如 ['text1', 'another text']:

    <h1 *ngFor="let txt of texts">{{txt}}</h1>
    

    这将生成两个带有数组值的 h1 标签。

    然后,如果将数组更改为 ['new text'],相同的 *ngFor 将更新,它只会生成一个带有 'new text' 值的 h1 标签,以及旧的 'text1' 和 'another text' h1 标签将从视野中消失。

    您可以在official documentation 中阅读更多相关信息

    在您的特定情况下,您正在向 DOM 添加元素,因此每次执行此操作时它都会创建一个新的模板实例。所以它在渲染整个数组时工作得很好。

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 2021-10-05
      • 2017-11-26
      • 2021-10-05
      • 1970-01-01
      • 2014-10-22
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多