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:
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?
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.
DOM stands for Document Object Model. AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.
AngularJS has directives for binding application data to the attributes of HTML DOM elements.
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.
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:
Instead of linking function Angular provides two mechanisms how you can access DOM:
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) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With