Full stack Web Development

An Extensive Introduction to Angular2 Decorators

Product Overview

Decorators is a special kind of declaration in angular2 which can be attached during class definition, method, accessory, property or parameter. To elaborate this, we need to discuss in depth.

Details

If you are aware of java syntax there is @annotations similarly here in, we have @decorators in TypeScript. Decorator will provide some information or metadata about the property, class, method, accessor or parameter. Suppose you are going to create some functions, classes, property and for all these we can attach decorators. So why?
Let’s understand how to create the decorators in our class definition.

class Acadgild{
Skills:string = “innovation_learning_System”;
}
let  Angular2=new Acadgild();
console.log(Angular2.skills);

Now attach a @customdecorators to class and save this file as decorators1.ts in your file structure. See the below image:

Here, I am using visual studio code  if you do not have then download it from the attached link. Visual studio code is the standardized code editor which is recommended by google to make Angular2 coding easier by using typescript language.
“According to the industry best standards visual studio code is the best editor to write our typescript code.”
What next?
Decorator concept wasn’t available in Javascript however in typescript it is introduced. Next is how we can attach decorator in our class file.
To do so, let see how we can attach.

@customDectorator
class Acadgild{
Skills:string = “innovation_learning_System”;
}
let  Angular2=new Acadgild();
console.log(Angular2.skills);

Normally in Java or in any other technologies annotation is been inbuilt so here I have used @customDectorator.
We can have any name for decorator. Now view the below image;

The moment I have used @customDecorator I have got an error.
To remove this error we need to do some changes in tsconfig.json file by attaching “experimentalDecorators”: true //for removing this warning.
If anyone doesn’t know what is tsconfig.json then let us discuss.
Tsconfig.json

  • This is the most important steps to follow because if we don’t have tsconfig.json file in our project then Angular2 can’t able to understand what to do.
  • In short it is a deployment descriptor which describe what Angular2 project’s needs.
  • It is the TypeScript compiler configuration file. It guides the compiler to generate JavaScript files.
  • tsc is a typescript compiler and –init is a command to create tsconfig.json file automatically in your folder structure.

We need to type in terminal
tsc  –init
After it successfully got created we can view it our file structure as:

So, we got this file in .json format.
To remove the error in class as we have included @customerDecortator as we need to add in the tsconfig.json file as :
I have now added “experimentalDecorators”: true in our tsconfig.json file.
 Now if we view our decorators1.ts file now it will show no error as we have fixed that error.

  Notes: “Decorators are actually functions”. So in order to use this @customDecorator we have to use the same name for creating the function. Let’s do that.
lets create the function using same name of @customDecorator


After creating the function definition of @customDecorator, we will again get one more error as:

We need to pass as an argument in function as:

Function customDectorator(target)
{
}
@customDectorator
class Acadgild{
Skills:string = “innovation_learning_System”;
}
let  Angular2=new Acadgild();
console.log(Angular2.skills);

What is Target?

Target is nothing but a class itself. So while creating a class decorator we are applying @customDecorator to class. In short @customDecorator is a class Decorator.
While passing or defining the class decorator, the whole class definition itself becomes the parameter or argument to the decorator definition.
Therefore, the target is nothing but a class itself.
Updates: The concept of decorator is an experimental feature in typescript. It wasn’t planned and Experimental support for decorators is a feature that is subject to change in a future release.
Now we can define some properties inside the @customDecorator function body definition. As I said target is a class and we can define the properties of the class  inside the function definition by :
We need to set the default property of class by using prototype:

Function customDectorator(target)
{
   target.prototype.skills='NewtechStack_holders';
}
@customDectorator
class Acadgild{
Skills:string = “innovation_learning_System”;
}
let  Angular2=new Acadgild();
console.log(Angular2.skills);


As we have already created the instance of a class by using the new operator.
Since I have applied @customDecorator so we access the skills of Acadgild class by:
console.log(Angular2.skills); //prints the skills
Output should come as  “innovation_learning_System”. Let us view it.

To compile it we need to type in terminal as:
tsc -w
After this .ts file will be got translated to .js file for browser rendering.

Then we will copy the .js file code and paste it in the console of the browser.

Note that we got “innovation_learning_System” as the output.
Now take out the skills and watch whether the prototype skills comes.

We didn’t added skills however we have our prototype default skills so, we can view the answer as “NewtechStack_holders”
Watch the output in console as:

You can view in the down we got the answer which we expected.
So, whenever you are creating a class decorator instances the skills property is by default available to no matters how many instances you will create for our example named AcadGild class.
Parameterized Decorators
Till now we have done class decorators now let’s understand what is parameterized decorators.
Let’s create an example for understanding.

@parameterizedDecorarator('')
class player2{
    skills:string
}

So we have created a @parameterizedDecorators(“”) empty parameter with a class as its definition.
Now let’s just create a function for the @parameterDecorarator(“”) that means we need to define our definition.

function parameterizedDecorarator(param1){
    return function(target){
     target.prototype.skills=param1;
     return target;
    }
}
@parameterizedDecorarator('')
class player2{
    skills:string
}

Here we have created the function definition for @parameterizedDecorarator(”).Explanation:
The parametrized Decorator needs to return a factory function.
r

eturn function(target){
     target.prototype.skills=param1;
     return target;
    }

This line has the parameter named target, Here the target is the class. The class properties can be defined inside the parameterized decorator by passing the reference.
While passing or defining the para decorator, the whole class definition itself becomes the parameter or argument to the decorator definition.
Therefore, the target is nothing but a class itself which is defined inside the factory method.
Now   target.prototype.skills=param1;  return target;
Here the target as I explained it is a class and prototype is the parameterized decorator where we are defining, as class is nothing but function. Therefore, the default value we are now passing from the parameterized decorator which is received by param1.
Then the moment we call the class by creating the object of a class.
Like this as

function parameterizedDecorarator(param1){
    return function(target){
     target.prototype.skills=param1;
     return target;
    }
}
@parameterizedDecorarator(''football”)
class player2{
    skills:string
}
let  obj2=new player2();
console.log(obj2.skills));//football

The instance got created now and we will get the answer after compilation of the code as football. Unless we set our own skills while calling Like this.

function parameterizedDecorarator(param1){
    return function(target){
     target.prototype.skills=param1;
     return target;
    }
}
@parameterizedDecorarator(''football”)
class player2{
    skills:string
}
let  obj2=new player2();
obj2.skills=”cricket”;
console.log(obj2.skills));//cricket

Now it is called object shadowing that means the prototype skills param1 which is passed won’t be shown as user seated his own skills therefore, the parent prototype skills won’t be shown.
After compilation we will get the .js file in our file structure.  View the below image. This a .ts file
Now after compilation we will get .js file as:

Let’s now copy this .js file into our browser console to get the answer.

As we see it provide the answer in our console. In this way we can make our class decorator which you can use in Angular2.
 

Property Decorators

Now, we will understand what is property decorator by using an example.

class player4{
    @GetSet
    skills:string;
}

Then we have applied one decorator name @GetSet.Here we have created a class named player4 and we got a property of the class name skills which is string type. Remember property decorator applies to a property.
What is @GetSet ?
Ans: @GetSet is a property decorator.
The next phase is we need to define this property decorator by passing two parameters now. Like this as below:

function GetSet(target,name)
{
//it take two parameter
//target is not a class now
//class prototype is the target
//second parameter is the skills from the class which is the
//property of class
console.log(name);
target.skills='cricket';
//here we don't write the prototype
}
class player4{
    @GetSet
    skills:string;
}

What is the target in property parameter  ?We define a function as GetSet(target,name){}. As we can see above there is two parameter passed to GetSet function. If we don’t pass the two parameters we will get an error.
Ans: Target is a not class here in this case because the class not a parameter to GetSet. Rather the class prototype is the parameter to the target.
So player4 is target now.
Now what is name in a property parameter?
Ans: This name is nothing but skills:string which we want to set.
Now if we print inside GetSet() function as console.log(name); we will get skills. Let see this :
After the compilation of .ts file we will get the .js file as:

Now let’s copy this code and paste it in our browser console.

The name shows the answer as skills.

Now if we set the skills =”cricket” and then after getting called by the created object we will  get the skills as “ cricket” . Initially the name prints skills and we set the skills so it will print the skills only.
We didn’t used prototype. As you see in case :
target.skills=”cricket”;
Because the parameter target is the prototype of GetSet function itself. Skills are already present in the prototype of the function.

function GetSet(target,name)
{
//it take two parameter
//target is not a class now
//class prototype is the target
//second parameter is the skills from the class which is the
//property of class
console.log(name);
target.skills='cricket';
//here we don't write the prototype
}
class player4{
    @GetSet
    skills:string;
}
Let obj4=new player4();
console.log(obj4.skills);//cricket

After the change and compiled by tsc-w we get the current js file and we need to copy this in our browser to get the answer as “cricket”.

See below we got cricket as the answer.

Conclusion:

There are few more decorator like method decorators parameter decorators but mostly we will use class decorators. Now we must have got some idea is why decorator is used before component as @component.
Enroll for Front-end Web Development Training conducted by Acadgild and become a successful Web developer.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close