Angular - Directives in Angular
Angular - Directives in Angular
Angular - Directives in Angular
Angular
Dashboard / My courses / Angular / Directives / Directives in Angular
Directives in Angular
Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below −
Component Directives
These form the main class having details of how the component should be processed, instantiated and used at runtime.
Structural Directives
A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf
and *ngFor.
Attribute Directives
Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below.
ng g directive active
The imported Directive symbol provides the Angular the @Directive decorator.
The @Directive decorator’s lone configuration property specifies the directive’s CSS attribute selector [appActive].
It is the brackets ([]) that make it an attribute selector. Angular locate each element in the template that has an attribute named appActive and
applies the logic of this directive to that element.The attribute selector pattern explains the name of this kind of directive.
Now, define the behavior of the directive. So we need to add code inside the constructor of an ActiveDirective class.
// active.directive.ts
Now, we can use the directive inside our HTML component. Write the following code in an app.component.html file.
192.168.0.102/mod/page/view.php?id=135&forceview=1 1/2
2/24/2020 Angular: Directives in Angular
ng serve
You can see that; we got the green background color of the text. Which is cool because we have first created the custom directive and add that
directive to our HTML element.
Here, we have modified the DOM through the angular directive. We have changed the color of p element through angular attribute directive.
Practice exercise
Exercise 1 : Change the above example to change the color of p element to blue.
Exercise 2 : Change above example to change the color as well as font of the p element to Red and font as "italic bold 20px arial,serif"
192.168.0.102/mod/page/view.php?id=135&forceview=1 2/2