An important guide on Angular Directives and their types
Harshal Suthar
Posted on March 20, 2023
What are Angular Directives?
Directives are instructions in the DOM that specify the way to place your components and business logic within Angular. These are basically custom HTML attributes that tell angular to alter the style or design or behavior of the DOM elements. Directives are building blogs of the angular applications.
Angular Directive is largely a category with a @Directive decorator. Decorators are methods that simply modify JavaScript classes.
What are the types of Angular Directives?
There are three kinds of Angular Directives:
- Components
- Attribute Directives
- Structural Directives
Components:
In component directives, there are three parameters.
(i) selector: It tells the template tag which specifies the beginning and end of the Component.
(ii) templateUrl: It specifies the template used for the component.
(iii)styleUrls: It consists of all the fashion format for the actual component.
Let’s understand component directive by Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
Attribute Directive
Attribute Directives listen and modify the behaviour of the DOM elements.
The most common attribute directives are following:
(i)NgClass:
NgClass adds and removes CSS classes to DOM elements. There are Expressions in the NgClass like;
(a) String: This CSS class would accept the string when passed.
Following is that the Example of String in NgClass:
Passing String in class:
<button>Button</button>
Passing String in class:
(b)Object: Passing the object in button as true in ngClass.
Following is that the Example of Object in NgClass:
Passing object in class:
<button>Button</button>
Passing object in class:
(c)Array: These CSS classes declared as array elements are added
Following is that the Example of Array in NgClass:
Passing Array in Class:
<button>Button</button>
Passing Array in Class:
(ii)NgStyle:
- It is used to style the properties of Angular.
- And many inline styles can be set simultaneously by binding the ngstyle.
Read More: Angular Login With Session Authentication
Following is an Example of NgStyle:
Hello! This is the Example of ngStyle directive
Hello! This is the Example of ngStyle directive
The Output of this Example is here:
The Output of this Example is here:
(iii)NgModel:
- NgModel is a directive that binds the input, select, checkbox, date picker, span, etc., and stores the specified variable.
- It is also used in the Form Variables.
- It is additionally applied in Form Validations.
- NgModel exported from the FormsModule.
- NgModel is an extremely useful concept within Angular.
- It is additionaly called Two-way Data Binding. Following is an example of NgModel:
You can see the code which is within the component.html file. In this example, we can bind the name with the ngModel.
<input type="text">
((NAME))
Now, we give the name variable within the component.ts file.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name='demo';
}
Another thing is, once we use NgModel, we must import FormModule in the app.module.ts file. This is shown in the following code.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from "@angular/forms";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Structural Directive
- Structural Directives are answerable for the structure and Layout of the DOM element.
- It won’t hide or display the items on the DOM elements.
- Structural Directives are easily identified using the ‘*’
There are three built-in structural directives:
(i) NgIf
(ii) NgFor
(iii)NgSwitch
(i)NgIf
- This Directive removes the HTML element if the expression is evaluated as false.
- If the statement is true, a copy of the Element is added in DOM.
Following is an example of ngIf Directive:
For example, let’s consider component.html file, here we have created a button with show/hide property. Next, we made a condition for showing or hiding the div.
<button>
Show/hide</button>
Div Content is here..
Then we move to component.ts file. Here, we have created the variable as isShown having Boolean datatype. By default, its value is set to false. Next, we made a button event name as toggleShow(). And here, we have performed the functionality on div to display it or not.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor() { }
ngOnInit(){
}
isShown:boolean=false;
toggleShow(){
this.isShown=!this.isShown;
}
}
And the output is here:
Next, when we click the show/hide button then div is shown and vice-versa. Here it is:
Want to Hire Trustworthy Angular Development Company? Your Search ends here.
(ii)NgFor
This Directive is used as a repeat Part of HTML Elements once per item from a Collection.
Following is an example of ngFor condition.
In the component.html file, we have created an array of Data with variables that bind them and created a loop for the data array.
{{login.login_id}} {{login.name}} {{login.designation}}
Next, we create an array with the variables in the compoenent.ts file.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
Data=[
{"login_id":101,"name":"ABC","designation":"Developer"},
{"login_id":102,"name":"DEF","designation":"Trainee"},
{"login_id":103,"name":"EFG","designation":"HR"},
{"login_id":104,"name":"HI","designation":"Engineer"}];
constructor() {
}
ngOnInit(){
}
}
Here is the output for that code:
(iii)NgSwitchCase
- NgSwitchCase displays one element from a possible set of elements based on conditions.
Here is an example of NgSwitchCase.
First, we create a Class for the login. which is named as login.ts.
export class login{
constructor(
public login_id:number,
public name:string,
public designation:string
){}
}
Then next, we make a SwitchCase in the component.html file.
In this HTML file, we make a for loop for the login data and then we perform a Switch Case for the values.
<select><option>
{{login.name}}
{{login.name}}
{{login.name}}
{{login.name}}
{{login.name}}
{{login.name}}
{{login.name}}</option>
</select>
Now, we make an Array of login in the component.ts file.
In the following example, we imported the login class here. Then we created an array of login and assign variables to it. However, the by-default SelectedValue would be ‘Abc’.
import { Component, OnInit } from '@angular/core';
import { login } from "./login";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
login:login[]=[
{login_id:1, name:"Abc",designation:"trainee"},
{login_id:2,name:"Def",designation:"developer"},
{login_id:3,name:"Mno",designation:"HR"},
{login_id:4,name:"Xyz",designation:"Tester"},
{login_id:5,name:"Ghi",designation:"Senior"},
{login_id:6,name:"Klo",designation:"QA"},
];
selectedlists?:login;
selectedvalue:string="Abc";
constructor() {
}
onSelect(login:login){
this.selectedlists=login;
}
ngOnInit(){
}
Here is the output of this Code:
All the names are shown in the dropdown.
Conclusion
Angular directives are contemplated as the building blocks of application and have great importance. In this blog, we have seen what are Angular Directives and their types. We use angular directives in the conditions, loops, for animating, etc. Angular directives are very useful in developing fascinating applications and operate a wide array of data smoothly.
Posted on March 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 31, 2024