首页 > 解决方案 > Angular 8 - 如何通过属性查询 DOM 元素?

问题描述

我有一个使用 renderer2 动态生成的 HTML 5 表:

const td = this.renderer.createElement('td');
this.renderer.setProperty(td, 'id', letter + i);
this.renderer.setAttribute(td, 'contenteditable', 'true');
this.renderer.setAttribute(td, 'r', i + '');
this.renderer.setAttribute(td, 'c', j + '');

该表具有以下结构

<table _ngcontent-iji-c1="" appcreatereport="">
<tr _ngcontent-iji-c1="">
<td _ngcontent-iji-c1="">1</td>
<td _ngcontent-iji-c1="" id="A1" contenteditable="true" r="1" c="1"></td>
<td _ngcontent-iji-c1="" id="B1" contenteditable="true" r="1" c="2"></td>
<td _ngcontent-iji-c1="" id="C1" contenteditable="true" r="1" c="3"></td>
<td _ngcontent-iji-c1="" id="D1" contenteditable="true" r="1" c="4"></td>
<td _ngcontent-iji-c1="" id="E1" contenteditable="true" r="1" c="5"></td>
</tr>
...

每个<td>都有一个“id”,一个行号“r”和一个列号“c”

我正在尝试仅使用角度(所以没有 jquery)并且我查看了许多现有的数据网格,但它们从未完全涵盖我计划做的事情,并且扩展它们似乎比构建我需要的东西更复杂。

我有两个问题。

  1. 我的理解是我不应该直接在 Angular 中操作 DOM,如果元素没有本地引用,我该如何访问它们?<td(或者当我在 renderer2 中生成 > 元素时如何添加本地引用。<TD>需要更新文本,例如当我从 excel 复制/粘贴时。
  2. 如何按属性查询元素,所以我想要 r=1 和 c=4 的元素(而不是通过 id“D1”查询)。我只找到了只适用于引用的@ViewChild。

我目前正在通过以下方式设置 TD 元素的文本:

(document.getElementById(
          'C1'
        ) as HTMLTableDataCellElement).innerHTML = '123;

我怎样才能以更“有角度”的方式做到这一点?

标签: angularrenderer

解决方案


最好的方法是更改​​设计以使用带有元素数组的表格和*ngFor. 要从页面中删除它,您可以使用*ngIf="elements.length === 0";

let elements = [{r:1, c: 1, value:''}, {r:1, c: 2, value:''} ... ];
elements[1].value = '123';

<td *ngFor="let el of elements" [r] = "el.r" [c]="el.c">{{el.value}}<\td>

td在这种情况下,您将可以使用元素数组直接访问每个值。

作为替代方案 -ng-template可用于将表格保存在 html 中,但直到需要时才显示。


推荐阅读