【问题标题】:Most performant way to add to DOM in ngFor在 ngFor 中添加到 DOM 的最高效方式
【发布时间】:2021-02-04 11:04:12
【问题描述】:

我有一个 websocket 并绑定到一个显示数据的 ngFor。列表大小约为 100 条记录。

我在每个条目上创建了一个按钮,并附加了一个单击方法,该方法在单击时创建加载div/spinner,同时执行一些其他逻辑。方法完成后,我从按钮/DOM 中删除“正在加载”div

我通过 d3 实现了这一点。问题是:

  1. 这是最有效/最正确的方法吗?
  2. 我已经阅读了 ViewChild 和 Renderer。我应该使用它吗?

我决定动态添加加载/微调器 div,而不是在不需要时添加到 DOM/HTML。

Stackblitz:https://stackblitz.com/edit/angular-zenqoe?file=src%2Fapp%2Fproduct-list%2Fproduct-list.component.ts

html:

<ul>
  <li *ngFor="let product of products">

    <h3>
      <a [title]="product.name + ' details'">
        {{ product.name }}
      </a>
    </h3>

    <button (click)="share(product)" id="btn-{{product.id}}">
      Share
    </button>

  </li>
</ul>

组件:

share(product) {
    window.alert(product.id);

    const btn = d3.select('#btn-' + product.id)

    btn.append('div')
    .class({'my-class': true})
    .text('Loading...');

    // Some extra logic
    // After logic is completed (via its .subscribe) remove element

    setTimeout(function(){   

       let divv = document.getElementById('btn-' + product.id)
       divv.remove()

    }, 3000); 

   
  }

【问题讨论】:

    标签: javascript angular d3.js ngfor


    【解决方案1】:

    ngFor 的每个元素都会注册多个事件。 使用事件冒泡在父 div 上注册并将子 id 传递给它以进行单个事件注册。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-07
      • 2012-11-28
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多