Angular – Attribute directives

Angular Attribute directives

What are Angular Attribute directives?

 Angular provides some built-in directive like  NgStyle, NgClass  etc.  These directives change the appearance and behavior of HTML elements. On the other hand we can also create our own custom directive depending on application need using @Directive() decorator. It has a selector metadata that defines the custom directive name,  and host is use to perform any action or event, what this directive actually does.

Built-in Angular Attribute directives:

1. NgStyle: 

The  NgStyle directive allow you apply style on properties of an DOM elements. With the help of variable you can apply style conditionally on attributes. Example of NgStyle Attribute directives:

nyStyle directive also allow to set individual style properties using the  [style.property]. You can direct set an style property by assigning any value or and function that return some valid value.

2. NgClass

With the help of  NgClass directive you can to set the CSS class dynamically  an DOM element. Example of NgStyle Attribute directives:

In the above example the keys is  the class which are added to the element if the value of the key evaluates to true. So if alert-success is true then same class will apply on div.

In this example you can see, conditionally apply classes depending on the variables values.  

Custom Attribute Directives:

Till now we have seen NgStyle and NgClass built in directive of angular. Now Angular provide ability to create oue own custom directive depending on our need. With the help of @Directive() decorator , we can also create our own custom directive. It has a  selector metadata that defines the custom directive name,  and host is use to perform any action or event, what this directive actually does.

Example of Custom Attribute directives:

1. woweffect.directiv.ts

In the above  code snippets we have create an directive with the help of @Directive() decorator, that tells to angular,  this is an directive class.  In this @Directive() decorator, we have selector and host metadata. Selector is used to declare directive name which we can use in our HTML element, and host is use to perform any action or event, what this directive actually does. On above Example wowEffect Directive is bind with  two event with the help of host metadata. Now Use that wowEffect Directive any element.

In your component.ts file please define an variable

Example of Attribute directives: