Attribute directive is used to change/modify the behavior of the HTML element in the Dom Layout. Its built-in type is NgStyle, NgClass. it is used to change the attributes of the existing HTML element. NgClass, NgStyle are the most used attribute directives.
NgStyle directive is similar to one of the data binding techniques called style binding in Angular. The main point is NgStyle is used to set multiple inline styles for the HTML element.
It is similar to NgStyle attribute but here it is using the class attribute of the HTML element to apply the style.
Here I added a button control in the template part with a style sheet named MyStyle(). This MyStyle css method is defined as below.
Code Ref. of app.component.ts for NgClass,
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'Satya-App',
- template: `<button class='colorClass' [ngClass]='applyClasses()'>Satyaprakash Samantaray</button>`,
- styles: [`.boldClass{
- font-weight:bold;
- font-size : 30px;
- }
-
- .italicsClass{
- font-style:italic;
- }
-
- .colorClass{
- color:Red;
- }`]
- })
- export class AppComponent {
- applyBoldClass: boolean = true;
- applyItalicsClass: boolean = true;
-
- applyClasses() {
- let classes = {
- boldClass: this.applyBoldClass,
- italicsClass: this.applyItalicsClass
- };
-
- return classes;
- }
- }
Code Description
In this NgClass we are using class attribute of HTML element to apply styles.
- template: `<button class='colorClass' [ngClass]='applyClasses()'>Satyaprakash Samantaray</button>`,
OUTPUT
Structural Directive
The structural directive is used to add or remove the HTML Element in the Dom Layout, typically by adding, removing, or manipulating elements... Its built-in types are *NgIf,*NgFor,*NgSwitch. Structural directives are easy to recognize by using an asterisk (*).
Difference between the structural directive and attribute directive
The structural directive is used to add or remove the Dom Element itself in the Dom Layout, whereas attribute directives are used to just change the attribute or appearance of the Dom element.
Types of built-in structural directive
NgIf
It is used to create or remove a part of the DOM tree depending on a condition.
NgFor
It is used to customize data display. It is mainly used for displaying a list of items using repetitive loops.
NgSwitch
It is like the JavaScript switch. It can display one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM.
Code Ref. of app.component.ts for implementation of NgIf
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'Satya-App',
- template: `<div style='color:blue' *ngIf="true">You can See Satyaprakash....</div>`
- })
- export class AppComponent {
-
- }
Code Description
Here If ngif= true the text will be visible on the web page.
- template: `<div style='color:blue' *ngIf="true">You can See Satyaprakash....</div>`
OUTPUT
Code Ref. of app.component.ts for implementation of NgFor,
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'Satya-App',
- templateUrl: './app.component.html',
- })
- export class AppComponent {
- employees: any[] = [
- {
- code: '1001', name: 'Satya', gender: 'Male',
- annualSalary: 5500, dateOfBirth: '25/6/1988'
- },
- {
- code: '1002', name: 'Mohit', gender: 'Male',
- annualSalary: 5700.95, dateOfBirth: '9/6/1982'
- },
- {
- code: '1003', name: 'Rohit', gender: 'Male',
- annualSalary: 5900, dateOfBirth: '12/8/1979'
- },
- {
- code: '1004', name: 'Satyaprakash Samantaray', gender: 'Female',
- annualSalary: 6500.826, dateOfBirth: '14/10/1980'
- },
- ];
- }
Code Description
I have created a class named employees and inserted values to its corresponding properties.
- employees: any[] = [
- {
- code: '1001', name: 'Satya', gender: 'Male',
- annualSalary: 5500, dateOfBirth: '25/6/1988'
- },
Code ref. of app.component.html for implementation of NgFor,
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta charset="utf-8" />
- <style>
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 100%;
- }
-
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
-
- tr:nth-child(even) {
- background-color: #dddddd;
- }
- </style>
- </head>
- <body>
- <table align="center" border="1" cellpadding="4" cellspacing="4">
- <thead>
- <tr>
- <th style="background-color: Yellow;color: blue">Code</th>
- <th style="background-color: Yellow;color: blue">Name</th>
- <th style="background-color: Yellow;color: blue">Gender</th>
- <th style="background-color: Yellow;color: blue">Annual Salary</th>
- <th style="background-color: Yellow;color: blue">Date of Birth</th>
- </tr>
- </thead>
- <tbody>
- <tr *ngFor='let employee of employees'>
- <td>{{employee.code}}</td>
- <td>{{employee.name}}</td>
- <td>{{employee.gender}}</td>
- <td>{{employee.annualSalary}}</td>
- <td>{{employee.dateOfBirth}}</td>
- </tr>
- <tr *ngIf="!employees || employees.length==0">
- <td colspan="5">
- No employees to show in the page....
- </td>
- </tr>
- </tbody>
- </table>
- </body>
- </html>
Code Description
Here NgFor is used to display a list of items using repetitive loops, that is, data of employees class.
- <tr *ngFor='let employee of employees'>
- <td>{{employee.code}}</td>
- <td>{{employee.name}}</td>
- <td>{{employee.gender}}</td>
- <td>{{employee.annualSalary}}</td>
- <td>{{employee.dateOfBirth}}</td>
- </tr>
OUTPUT
Code Ref. of app.component.ts for implementation of NgSwitch,
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'Satya-App',
- template: `<h2>{{title}}</h2>
- <p *ngIf="showElement">Show Element</p>
- <div [ngSwitch]="inpvalue">
- <p style='color:blue' *ngSwitchCase="1">You have selected M S Dhoni</p>
- <p style='color:blue' *ngSwitchCase="2">You have selected Sachin Tendulkar</p>
- <p style='color:blue' *ngSwitchCase="3">You have selected Satyaprakash Samantaray</p>
- <p style='color:red' *ngSwitchDefault>Sorry! Invalid selection....</p>
- </div>`
- })
- export class AppComponent {
-
- inpvalue: number = 3;
- }
Code Description
You can display one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM. Here we are using ngswitchcase to apply switch case and ngswitchdefault is for invalid selection. Using ngswitch directive we can show output by passing the value of inpvalue property in AppComponent class.
OUTPUT
For valid selection >>
You can check code compilation status in command prompt during the change in code using Visual Studio.
Custom Attribute
We can create custom attribute directives and custom structural directives using a @Directive decorator. Using custom attribute directive we can change appearances such as text color, background color and font size of the body of an HTML element that can be called host element. To change appearance angular provides ElementRef class that can directly access DOM.
Benefits of using custom directive:
It is vulnerable to XSS attacks when we directly use ElementRef in our application. It is better to create a custom directive and use ElementRef inside directive to change appearance or behavior of the host element.
Steps to be followed to create custom attribute directive
- Create a class decorated with @Directive.
- Assign the attribute directive name to the selector metadata of @Directive decorator.
- Use ElementRef class to access DOM to change host element appearance and behavior.
- Use @Input() decorator to accept user input in our custom directive.
- Use @HostListener() decorator to listen to events in custom attribute directive.
- Configure custom attribute directive class in application module in the declarations metadata of @NgModule.
Steps to be followed for customization of project structure and code
Create a folder under app called directives. Under directives create a file called red.directive.ts.
Code Ref. ofred.directive.ts
- import { Directive, ElementRef } from '@angular/core';
-
- @Directive({
- selector: '[myRed]'
- })
- export class MyRedDirective {
- constructor(elRef: ElementRef) {
- elRef.nativeElement.style.color = 'red';
- }
- }
Code Description
We are creating a directive named as myRed directive. When we use it with HTML elements such as <p> and <div>, the text color within that element will be red.
The class should be decorated with @Directive. The role of @Directive is to mark a class as an angular directive and to collect directive configuration metadata.
To define a directive name, we need to use metadata selector and assign a directive name enclosed with the bracket [ ], for example [myRed]. We should not use any keyword as a directive name which is reserved by angular and we should also not start the directive name with ng.
Create a constructor in the class to get the instance of ElementRef by dependency injection. Using ElementRef we can access the DOM element and can change their appearance and behavior.
To use our custom directive anywhere in our angular application, we need to configure it in application module in the same way as we configure the component.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppComponent } from './app.component';
- import { MyRedDirective } from './directives/red.directive';
-
- @NgModule({
- declarations: [
- AppComponent,
- MyRedDirective
- ],
- imports: [
- BrowserModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Code Ref. of app.component.ts
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'Satya-App',
- templateUrl: './app.component.html'
- })
- export class AppComponent {
- txtsize = '25px';
- colors = ['CYAN', 'GREEN', 'YELLOW'];
- myColor = '';
- }
Code Ref. Of app.component.html
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <meta charset="utf-8" />
- <style>
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 100%;
- }
-
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
-
- tr:nth-child(even) {
- background-color: #dddddd;
- }
- </style>
- </head>
- <body>
- <p myRed>Custom Attribute Directive By Satyaprakash</p>
- </body>
- </html>
Code Description
We are ready to use our directive in the HTML template. Find the code snippet.
- <body>
- <p myRed>Custom Attribute Directive By Satyaprakash</p>
- </body>
Code ref. of app.module.ts
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppComponent } from './app.component';
- import { MyRedDirective } from './directives/red.directive';
-
- @NgModule({
- declarations: [
- AppComponent,
- MyRedDirective
- ],
- imports: [
- BrowserModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Code Description
Here I import custom attribute directive reference to configure the custom attribute I have created.
- import { MyRedDirective } from './directives/red.directive';
-
- @NgModule({
- declarations: [
- AppComponent,
- MyRedDirective
- ],
OUTPUT
SUMMARY
- Types of directives with examples.
- Different ways to create an Angular 6 project using Angular CLI – Command Prompt and Visual Studio Code.