javascript - 我们如何以角度向 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', '');
}
有没有人可以帮我解决这个问题?提前致谢。
编辑
我已经使用 jquery ( https://stackblitz.com/edit/angular-ivy-syoi3w?file=src/app/iframe/iframe.component.ts ) 在 iframe 元素中实现了拖动功能,这个 slackBlitz 示例面临 jqueryUi 的问题库。
解决方案
简单的答案是否定的,你不能在 Angular 中做到这一点。$compile
通过使用该服务,您可以在旧的 angular.js 中寻找什么。例如:
element.setAttribute('cdkDrag', '');
$compile(element)($scope);
但是,出于许多充分的理由,Angular 团队决定在新框架中放弃对这种动态方法的支持。
在 Angular 的前几个 RC 版本中,有一些变通方法/黑客基于这些方法DynamicComponentLoader
可以实现对 DOM 元素的动态指令编译,但后来DynamicComponentLoader
也被弃用,然后被删除。
推荐阅读
- javascript - Discord API 错误:无法发送空消息
- python - 迭代列表时如何将索引标记为“已使用”?
- yaml - YAML 中的可重复列表项
- xamarin.ios - Xamarin 应用无法在 iPhone 上以发布模式运行(无法安装此应用,因为无法验证其完整性)
- java - 使用 simpleJdbcCall 时数据库从 oracle 迁移到 postgresql 存储过程调用异常
- blogs - Docusaurus 博客列表,包括作者和图片
- heroku - Heroku 上套接字模式下的 Bolt-js 失败并出现错误 R10
- c# - SQL Server 连接字符串中的默认用户名和密码
- python - Django(2.1.1 版)升级到 Django(3.2 版)后管理面板更改
- r - 如何在 R 的 for 循环中制作数据帧?