angular - 什么是 Angular 中访问 DOM 元素的 `link` 函数的等价物

标签 angular typescript dom d3.js angularjs-directive

有在 Angular 2 指令上设置 link 属性以注册转换 DOM 的回调的示例。

一个示例是为 D3.js 图形创建指令。看这个pen :

enter image description here

link属性:

Directives that want to modify the DOM typically use the link option to register DOM listeners as well as update the DOM. It is executed after the template has been cloned and is where directive logic will be put.

Angular 4 指令的 API 非常不同。 Angular 4 中如何实现类似的功能?

最佳答案

在 AngularJS 中有 2 个阶段:编译和链接。 AngularJS 允许您挂接到这些阶段并在编译阶段执行自定义 DOM 修改,并在链接阶段执行应用程序模型(作用域)和 DOM 元素之间的绑定(bind)。这就是指令定义对象 (DDO) 具有这些键的原因:

app.directive('name', function() {
   return {
      compile: () => {}
      link: () => {}

Angular 在这方面是不同的。编译器现在将编译和链接作为一个阶段执行,您无法 Hook 该过程。您可以在以下文章中阅读更多相关信息:

Angular 提供了两种访问 DOM 的机制,而不是链接函数:

  • 查询 (@ViewChildren) - 主要由组件使用
  • 将 DOM 元素注入(inject)到构造函数中——主要由指令使用

您可以阅读有关查询的更多信息 here .这是将 DOM 元素注入(inject)指令的示例:

@Directive()
export class MyDirective {
   constructor(el: ElementRef) {}

关于angular - 什么是 Angular 中访问 DOM 元素的 `link` 函数的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248402/

相关文章:

javascript - subscribe() 后获取返回变量的值

JavaScript 运行时错误 : appendChild() - Unexpected call to method or property in IE8

javascript - HTML如何删除标签而不是内容

javascript - AJAX html stub ——加载清除的 head 元素是否实用?

angular - 如何动画 :enter & :leave transitions conditionally in Angular?

javascript - "module": "esnext" in tsconfig. json没有去掉Dynamic Lazy load模块报错

angular - 使用 DomSanitizer 后,图片网址仍然不安全

angular - HTTP 使用 firebase Id_token 从 API 获取 Angular 4

node.js - angularfire2安装和设置期间出现错误

typescript - 将 JSON 转换为 TypeScript 对象的最佳方法是什么?