angular - 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)并且我查看了许多现有的数据网格,但它们从未完全涵盖我计划做的事情,并且扩展它们似乎比构建我需要的东西更复杂。
我有两个问题。
- 我的理解是我不应该直接在 Angular 中操作 DOM,如果元素没有本地引用,我该如何访问它们?
<td
(或者当我在 renderer2 中生成 > 元素时如何添加本地引用。<TD>
需要更新文本,例如当我从 excel 复制/粘贴时。 - 如何按属性查询元素,所以我想要 r=1 和 c=4 的元素(而不是通过 id“D1”查询)。我只找到了只适用于引用的@ViewChild。
我目前正在通过以下方式设置 TD 元素的文本:
(document.getElementById(
'C1'
) as HTMLTableDataCellElement).innerHTML = '123;
我怎样才能以更“有角度”的方式做到这一点?
解决方案
最好的方法是更改设计以使用带有元素数组的表格和*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 中,但直到需要时才显示。
推荐阅读
- java - Java Android 开发“SSL 库失败,通常是协议”
- c - 使用 netlink 从旧内核上的套接字获取 inode
- javascript - 尝试使用我自己的 webpack 配置在 .vue 文件中获取本地图像时出错
- angular - 如果在 Angular 8 中输入的数字少于 10 位,则将类添加到输入
- c++ - 在 Visual Studio 2019 中使用 Qt 时出错
- python - 如何在 python 中使用 ccxt 制作币安期货订单?
- r - 如何仅将 lapply 用于函数的一个特定参数?
- android - 应用程序图标徽章未显示 Android
- android - 如何在 Android 中从 JSON 中提取数据
- ruby-on-rails - 使用 Rails 6 获取未定义的方法“add_role”,使用 UUID 进行 Rolify