Updated March 28, 2023
Introduction on Angular 2 Directives
Angular 2 is much simpler than its previous version. Directive is one of the major points which is now easier to create and maintain. In angular previous version, they are very difficult to create and maintain so many people avoid them to use. But angular2 makes it easy and more readable. In angular 2 directives provide more features and are more flexible as compared to Angular 1.x > in Agular 2 directive provides as simplicity and make code maintainable and readable for the developer. Also, the code is independent.
In angular 2 components is type of directive or we can say custom directive. Whenever we want to render any HTML file we instruct angular 2 application that this place we want to render our template for this component.
Types of Directives in Angular 2
In Angular 2 we have three types of directive which are described below:
Let’s discuss them one by one:
1. Attribute Directive
It modifies the behavior or appearance of the HTML element. Some of the built-in directive available are ngClass, ngStyle. This directive modifies the DOM element. Below is an example to show the syntax and working.
Code:
app.component.ts
import { app.component.ts
Component,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name:String = 'This is directive demo to modify the behaior and apperence of element.';
ChangeValue(data:String){
this.name=data;
}
technology=[
{techName:"JAVA", experienceLevel:"3 Years"},
{techName:"Spring Boot", experienceLevel:"2 Years"},
{techName:"Microservices", experienceLevel:"2 Months"}
];
}
app.component.html
<div [ngStyle]="{'width':'450px', 'margin-left':'150px','border':'4px solid #7142f4'}">
<h3 [ngStyle]="{'color':'#42f46e','font-size':'26px'}">
{{name}}
</h3>
<h3>I am working on these technologies</h3>
<table [ngClass]="'table'">
<tr><th>Technology</th><th>Experiences</th></tr>
<tr *ngFor="let data of technology">
<th>{{data.techName}}</th><th>{{data.experienceLevel}}</th>
</tr>
</table>
</div>
app.component.css
.customStyle{
color: blue;
font-size: 24px;
width:300px;
height: 30px;
margin-top: 50px
}
.table{
font-size: 24px;
font-family: Cambria, Cochin, Georgia, Times, Times New Roman, serif;
color:white;
margin-left: 100px
}
.table tr:nth-child(even) {
background-color: #87b793;
}
.table tr:nth-child(odd) {
background-color: #a187b7;
}
In the above example, we are using ngClass and ngStyle to change and apply the CSS to particular DOM element without writing too many lines of code.
Output:
2. Structural Directive
This Directive is used to change the structure of the element. It basically alters the DOM element, by using this we can add, delete and replace the element with a new element. It modifies the DOM layout.
Structural Directive includes ngIf, ngFor, and ngSwitch to change the layout of the DOM element.
Code:
app.component.ts
import { Component,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name:String = 'This is directive example';
count:number=10;
show:boolean=true;
toggle(){
this.show=!this.show;
}
ChangeValue(data:String){
this.name=data;
}
technology=[
{techName:"JAVA", experienceLevel:"3 Years"},
{techName:"Spring Boot", experienceLevel:"2 Years"},
{techName:"Microservices", experienceLevel:"2 Months"}
]
}
app.component.html
<div [ngStyle]="{'width':'450px', 'margin-left':'150px','border':'4px solid #7142f4'}">
<h3 [ngStyle]="{'color':'#42f46e','font-size':'26px'}">
{{techName}}
</h3>
<h3>I am working on these technologies</h3>
<table [ngClass]="'table'">
<tr><th>Technology</th><th>Experiences</th></tr>
<!-- ngFor Exampl e -->
<tr *ngFor="let data of technology">
<th>{{data.techName}}</th><th>{{data.experienceLevel}}</th>
</tr>
</table>
<input type="button" (click)="toggle()" value="Toggle Div"/>
<br/>
<!-- ngIf Example -->
<div *ngIf="show">
<div >This will show usage of ngIf</div>
</div>
<br/>
<input type="text" name="data" [(ngModel)]="count"/>
<br/>
<!-- ngSwitch Example -->
<div [ngSwitch]="count">
<p *ngSwitchCase="10">Your Value is 10 </p>
<p *ngSwitchCase="100">Your Value is 100 </p>
<p *ngSwitchDefault>Your Value is Not 10 or 100 </p>
</div>
</div>
app.component.css
table {
width: 100%;
}
example-container {
display: flex;
flex-direction: column;
}
.example-container > * {
width: 100%;
}
.example-card{
width: 50%;
}
Output:
3. Component Directive
We cannot create an angular2 application without components. Now we can have a closer look at how this component work and what type of metadata it contains.
we have to follow some steps to create a component in angular 2. Which are as follows:
- Create a class annotation with @Component annotation. In this, we set various metadata property so that this class can be identified as angular 2 components.
- Export this class. This will contain the business logic and server calls to get data. It will also contain angular 2 in the build method which will automatically get invoke during the life cycle of the angular component.
- We may require the different libraries and other components, in order to use them we need to import them by specifying their path.
Example to call component and render template.
Code:
app.component.ts
import { Component, Inject, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
btnClick() {
alert('You clicked me!');
}
}
app.component.html
<h3>Example to render component.</h3><button (click)="btnClick()">Press me.</button
app.component.css
table {
width: 100%;
}
example-container {
display: flex;
flex-direction: column;
}
.example-container > * {
width: 100%;
}
.example-card{
width: 50%;
}
Output:
Properties of Component Directive
@Component annotation contains many metadata properties inside it lets discuss them one by one:
1. selector: It is the name of the component. It should be unique throughout the application, two angular components cannot have the same name as the selector. Because we use this selector to render our view to the user. then our HTML methods and functions invoke our business logic on events.
2. templateUrl: This templateUrl is nothing but the HTML page. Here we need to provide the correct path of our HTML page otherwise it will give as an error. We can only have one HTML page at one time.
3. styleUrls: This styleUrls are the array of CSS. In which we can have any number of CSS inside it. But again here path has been correct.
4. Providers: These providers are optional, basically it depends upon the business requirement whether we want to call any service in the current component or not. This is the injectable class in angular 2.
Conclusion
So as compared to angular previous version, the Angular 2 directive is much more easier to maintain and create. They are independent, also they reduce the line of code and do not make the HTML or component or CSS non-readable. In angular 2 creation of custom, the directive is very much easy for example component directive is the best example for this. By this, we can render more than one component inside one component.
Recommended Articles
This is a guide to Angular 2 Directives. Here we discuss the Introduction to Angular 2 Directives and along with its different types like Attribute Directive, Structural Directive, Component Directive. You can also go through our other suggested articles to learn more –