Anu*_*.C. 4 javascript ng2-dragula angular
我正在处理 angular 4 项目,我需要拖动项目,所以我使用 ng2-dragula 插件为我做这件事。现在我需要在下降到特定位置后从每一行中提取 data-id 属性。
dragulaService.drop.subscribe(
(args) =>{
const [bagName, elSource, bagTarget, bagSource, elTarget] = args;
console.log('after', $(bagSource)); // element after the inserted element
});
Run Code Online (Sandbox Code Playgroud)
在 $bagSource 变量中,我将按新顺序获取每一行。说是
<tr attributes data-id="23"><tr>
<tr attributes data-id="2"><tr>
<tr attributes data-id="32"><tr>
Run Code Online (Sandbox Code Playgroud)
我如何从每个 tr 字段中提取数据 ID。我需要以数组中的新顺序获取每个 id。我要求的结果应该是 [23,2,32];
jquery $(element).attr("data-id") 等效于 angular 4。
jquery $(element).attr("data-id")使用@ViewChild一些老式的 javascript可以实现类似的功能。它看起来像:
使用这个只有当drag zone和table不相关(如果是使用@ user3263307回答它更Angular-friendly)。然而,最好的选择是使用[attr.data-id]="someVariable",但由于我不知道您的应用程序结构无法帮助您实现此方法。
<table #tableRef>
<tr attributes [attr.data-id]="23"><tr>
<tr attributes [attr.data-id]="2"><tr>
<tr attributes [attr.data-id]="32"><tr>
</table>
Run Code Online (Sandbox Code Playgroud)
很简单#tableRef,就像模板变量一样,angular 将在组件文件中与 @ViewChild 绑定。
@ViewChild() tableRef: ElementRef;
public getIds() {
if (!this.tableRef|| !this.tableRef.nativeElement)
return;
//assuming that table would have only one `tbody` tag.
let tableBody = this.tableRef.tBodies[0];
if (!tableBody)
return;
// we need to use Array.from, because `.children` returns HTMLCollection<Element>
// type which is not handy to iterate through it.
let childs: Array<HTMLTableSectionElement> = Array.from(tableBody.nativeElement.children);
let arrIds = [];
for(let child of childs) {
if (!(child.nodeName && child.nodeName.toLowerCase() == "tr"))
continue;
arrIds.push(child.dataset.id);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个有点残酷的角度方法,因为最好不要干扰 HTML DOM 结构。然而,只要我们只从元素中获取数据,一切都应该没问题。
请注意使用@ViewChild.
当需要直接访问 DOM 时,将此 API 用作最后的手段。改用 Angular 提供的模板和数据绑定。或者,您可以查看 Renderer2,它提供了即使在不支持直接访问本机元素时也可以安全使用的 API。依赖于直接 DOM 访问会在您的应用程序和渲染层之间创建紧密耦合,这将导致无法将两者分开并将您的应用程序部署到 Web Worker 中。
来自
Angular docs链接
| 归档时间: |
|
| 查看次数: |
11788 次 |
| 最近记录: |