Angular 中的 `link` 函数等效于访问 DOM 元素的什么

What is the equivalent of `link` function in Angular to access DOM elements

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

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

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.

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

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

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

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

代替链接函数 Angular 提供了两种访问机制 DOM:

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

您可以阅读有关查询的更多信息 here。下面是将 DOM 元素注入指令的示例:

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