首页 > 解决方案 > 我们如何以角度向 DOM 元素(来自 ts 文件)注入属性指令

问题描述

是否可以使用 setAttribute() 向 DOM 元素添加指令?

我试图通过材料拖放在我的组件中实现拖放。它正在工作,当我这样尝试时

<div class="example-boundary">
<div class="example-box" #test cdkDragBoundary=".example-boundary" cdkDrag>
    I can only be dragged within the dotted container
</div>

据我了解,拖动功能通过cdkDrag属性指令起作用。

当我尝试通过 setAttribute() 添加此指令时,它不起作用

constructor(private _renderer: Renderer2, private _elRef: ElementRef) {}

ngAfterViewInit(): void {
   let requiredElem = this._elRef.nativeElement.querySelectorAll('.example-box');
   this._renderer.setAttribute(requiredElem[0], 'cdkDrag', '');
}

当我检查 DOM 时,似乎添加了 cdkDrag。 在此处输入图像描述

有没有人可以帮我解决这个问题?提前致谢。

编辑

我已经使用 jquery ( https://stackblitz.com/edit/angular-ivy-syoi3w?file=src/app/iframe/iframe.component.ts ) 在 iframe 元素中实现了拖动功能,这个 slackBlitz 示例面临 jqueryUi 的问题库。

标签: javascriptangularangular-materialdrag-and-dropdom-manipulation

解决方案


简单的答案是否定的,你不能在 Angular 中做到这一点。$compile通过使用该服务,您可以在旧的 angular.js 中寻找什么。例如:

element.setAttribute('cdkDrag', '');
$compile(element)($scope);

但是,出于许多充分的理由,Angular 团队决定在新框架中放弃对这种动态方法的支持。

在 Angular 的前几个 RC 版本中,有一些变通方法/黑客基于这些方法DynamicComponentLoader可以实现对 DOM 元素的动态指令编译,但后来DynamicComponentLoader也被弃用,然后被删除。


推荐阅读