Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

There are examples of setting the link attribute on Angular 2 directives to register callbacks that transform the DOM.

An example is creating directives for D3.js graphs. See this pen:

enter image description here

The link attribute:

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.

The API for Angular 4 directives is very different. How is similar functionality achieved in Angular 4?

like image 456
conner.xyz Avatar asked Sep 15 '17 22:09

conner.xyz


People also ask

What is Link function is used for in angular?

link function is basically used to manipulate the DOM( Document Object Model ) element using custom directive. link option in custom directive registers DOM listener and also update the DOM. Watch the live demo or download code from the link given below.

What is DOM element in angular?

DOM stands for Document Object Model. AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.

Can we use DOM in angular?

AngularJS has directives for binding application data to the attributes of HTML DOM elements.

What is the difference between a link and compile in angular?

Explain what is the difference between link and compile in angular. js? Compile function: It is used for template DOM Manipulation and collect all of the directives. Link function: It is used for registering DOM listeners as well as instance DOM manipulation.


1 Answers

In AngularJS you have 2 phases: compilation and linking. And AngularJS allows you to hook into these phases and perform custom DOM modification during compilation phase and binding between app model (scope) and DOM elements during linking phase. That's why the Directive Definition Object (DDO) has these keys:

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

Angular is different in that respect. Compilation and linking is performed as one phase now by the compiler and you don't have a way to hook into that process. You can read more about it in the following articles:

  • Exploring Angular DOM manipulation techniques using ViewContainerRef
  • Angular’s $digest is reborn in the newer version of Angular
  • Here is what you need to know about dynamic components in Angular

Instead of linking function Angular provides two mechanisms how you can access DOM:

  • Queries (@ViewChildren) - mostly used by components
  • DOM element injection into constructor - mostly used by directives

You can read more about queries here. Here is an example of injecting DOM element into a directive:

@Directive()
export class MyDirective {
   constructor(el: ElementRef) {}
like image 153
Max Koretskyi Avatar answered Sep 24 '22 22:09

Max Koretskyi