Angular 2+ Decorators

PAUL DAVIES
2 min readJun 13, 2019

--

Friends, another great day to document decorators in angular.

What is a decorator in angular?

A decorator is just a function. The question now should be; what kind of function? It is a function that is used to wrap another function or a class. As a result, it does some tasks or manipulations as may be required then returns the original function.

What this means is that the decorator function gives us an opportunity to do some things handy before executing a certain course of the program.

Let us look at the screen below:

The circled in yellow color is a decorator. In this case a @Component decorator. In it is metadata which we shall discuss later but in brief, it contains CSS selector for the tag app-root, html template url and css url as well.

The @Component decorator is decorating the class AppComponent. What that means is that the application will first execute anything in that decorator before returning to the class. Also, it is a very special decorator in angular because it informs angular that this particular file is an angular component.

Look at another decorator circled in blue. It is decorating the function log. The function received two numbers which it multiplies and returns the result. As I said earlier, the decorator wraps a function or a class. So at run time, the decorator @log will be executed first. And in this case, the execution shifts to the function circled in yellow, just above the component decorator.

The decorator function takes three arguments. The target, name and descriptor as described below:

Target- is the decorated function(s).

Name- the name of the decorated function(s).

Descriptor- the original function.

What is the decorator function log doing?

It first logs the arguments

Then stores the original function value, just in case we might want it.

Overrides the original function with a new function which uses the original arguments to do the original multiplication. This was simply my implementation but you can do any kind of override and get any output you want.

It is as a result of decoration that angular is able to do data binding to the templates in use.

Guys, that is our documentation for today and I would like your views on this or any editing required to make it better. Good day and see you in the next article.

--

--

PAUL DAVIES
PAUL DAVIES

Written by PAUL DAVIES

Software Developer; Java, Angular2+,RxJS,Spring boot,Android

No responses yet