Thursday, October 26, 2023

Custom Directive in Angular Application Example

 How to create custom directive in Angular Application.

Directive class created by developer towards the requirement of an application
is called "custom directive".

custom directives are mostly application specific, this will be reusable across
 different components with in an application

*syntax:
   @Directive({
       selector:'[selectorname]'
             })
   export class <directiveclassname>
   {
    constructor(el:ElementRef)
    {
       manipulate html element using element ref
     }
    }
 ->element ref is providing native Element prop, this prop can be used
   to reference html element applied with directive


Steps to work with custom directive:
 1.create a directive
 2.place directive into a module
 3.apply directive to html element
   syntax:
       <tagname directive>..</tagname>



Requirement

  register component------> User Registration[title]-->back color-black
                                                          color -white
                                                          width -30%

  logincomponent    ------> User Authentication[title]-->backcolor-black
                                                          color-white
                                                          width-30%
          ....
                                            |
                                 repetition of styling towards a title
                                 in different components
                                            |
                                 this repetition can be avoided by creating
                                  a title directive


Example

ng g d title --flat
*this will create a directive class and will be imported and placed into
 app module declarations automatically

goto title.directive.ts


goto title.directive.ts

import { Directive,ElementRef } from '@angular/core';

@Directive({
  selector: '[appTitle]'
})
export class TitleDirective {

  constructor(el:ElementRef) {
    el.nativeElement.style.backgroundColor="black"
    el.nativeElement.style.color="white";
    el.nativeElement.style.width="30%";
   }
}

Create a component and call that above directive

.html


<h2 appTitle>Rajakonda Uday Kumar</h2>
<h3 appTitle>Hyd</h3>


Output




Note:
-----
In the above case apptitle directive instance will be created for h2 and h3,el.nativeelement
 will provide access to h2|h3,this tags will be applied with styling[background color,..]



Directive with input property:

Directive can receive data from template[html element] using input property.

Syntax:


  @Input()
   <prop name>:<datatype>;

  template                                                               directive
      |                                      |
  <tag name                                                             @Input()
    directive  prop name="value"----------->                <prop name>:..;


Example

Create a custom directive 







custom directive changes

import { Directive,ElementRef,OnInit,Input } from '@angular/core';

@Directive({
  selector: '[appTitle1]'
})
export class Title1Directive implements OnInit
{
  @Input()
  textcolor:string | undefined;

  constructor(private el:ElementRef)
  {
    this.el.nativeElement.style.backgroundColor="black";
    this.el.nativeElement.style.width="30%";
  }

  ngOnInit(): void
  {
      this.el.nativeElement.style.color=this.textcolor;
 }
}


.HTML Changes

<h2 appTitle1 textcolor="white">Rajakonda Uday kumar</h2>
<h3 appTitle1 textcolor="yellow">Ameerpet,Hyd</h3>

Output












Note:
----
*If input property name is same as directive name then we can input data directly to directive

goto title1.directive.ts
      [replace textcolor with appTitle1]


import { Directive,ElementRef,OnInit,Input } from '@angular/core';

@Directive({
  selector: '[appTitle1]'
})
export class Title1Directive implements OnInit
{
  @Input()
  appTitle1:string | undefined;

  constructor(private el:ElementRef)
  {
    this.el.nativeElement.style.backgroundColor="black";
    this.el.nativeElement.style.width="30%";
  }

  ngOnInit(): void
  {
    this.el.nativeElement.style.color=this.appTitle1;
   }
}



.html changes

<h2 [appTitle1]="'white'">Rajakonda Uday Kumar</h2>
<h3 [appTitle1]="'yellow'">Ameerpet,Hyd</h3>

Execution Flow


constructor will be executed before input property initialization
*ngOnInit method will be executed automatically[like constructor] after
 input property initialization,this method comes with OnInit interface

    <h2 appTitle1  textcolor="white">
           |
     Title1Directive class instance[textcolor-""]
           |
     constructor exec
     {
     this.el.nativeElement.style.color=this.textcolor;
     }                                       |
                                             "" 
           |
     input property initialization[textcolor="white"]
           |
     ngOnInit method exec
     {
        this.el.nativeElement.style.color=this.textcolor;
     }                                      |
                                                                     white





Directive with event handling:
------------------------------
*Directive can handle html element event using Host Listener decorator
*syntax:
  @HostListener('eventname')
   <methodname>()             <----------------- <button directive>text</button>
   {
     ...
   }

Host Listener will register a directive class method to html element event

Requirement:

register component----->button[register]------yellow back color for mouse enter
                                                                   bisque    "       "  mouse leave


login component  ------>button[login]   --->yellow back color for mouse enter
                                                               bisque    "       "  mouse leave
                                                 |
                                repetition of mouse enter and mouse leave                               
                                events code across different components
                                                        |
                                                the solution is custom directive


Example

create a directive to handle mouse enter and mouse leave events of html element









Directive Changes

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appHover]'
})
export class HoverDirective {

  constructor(private el:ElementRef) {
    this.el.nativeElement.style.width="30%";
   }
   @HostListener('mouseenter')
   onmouseenter(){
    this.el.nativeElement.style.backgroundColor="yellow";
   }

   @HostListener('mouseleave')
   onmouseleave(){
    this.el.nativeElement.style.backgroundColor="bisque";
   }
}


.html Changes

<button appHover>Register</button>
<br>
<h2 appHover>New Tutorials</h2>

Output



Angular Application Routing

Routing in Angular

The Angular Routing is a mechanism which is used for navigating between pages and displaying appropriate component or pages on the browser.

It also allows us to maintain the state, implement modules, and then loads the modules based on the roles of the user. 

Mapping client request URL path to a component is called routing, this
 will load component dynamically for presentation
   (or)
 Loading one component into another component dynamically is called
 "routing"

Routing provides navigation with in angular app

Website with single main page and other pages will be loaded as a part
 of mainpage without reloading|refreshing mainpage is called
 SPA
    (or)
 Single webpage of a website is providing access to all the content of website
 is called SPA

SPA advantages:
 1.faster response
 2.reducing burden on server [better performance]
 3.client can work offline with the data available in client system

*angular is providing set of classes | directives with RouterModule with @angular/router package to work with routing


1.Route class--this is used to create a route with path and component

2.Routes class--this is used to create a collection of routes
    syntax:
     const routes: Routes=[
                                {path:'path1',component:component1},
                                {path:'path2',component:component2,
                                 children:[
                                               {path:'cpath1',component:ccomponent1},
                                                  ...
                                              ]},
                                               { ... },
                               {path:'',component:..},
                               {path:'**',component:...}
                             ];

path:'' will be considered for initial component presentation with in main page

path:'**' will be considered for invalid route path

->children routes will provide inner navigation
            mainpage
      home ...   services [parent level navigation]
                     |
      training  ---------   training info
 
      consultancy---------       ....
           [children navigation]
     
->routes collection should be loaded into a module using
       RouterModule.forRoot method

Understanding Angular Routing 
Assume, that , I have two links

Employee Details

Department Details


When , we click on the Employee Details, we need to display the Employee Details,












Similarly when we click on the Department Details, we need to display the Department Details




Creating Employee Details Component:







Employee Details . html Changes







Creating a Department Component







Department Details (html)





Adding Routing in Angular:

When you are creating an angular application, at the time of creation it is asking whether you want to add angular routing to your project or not. If you select yes, then it automatically add the routing model in your project. If you select no then you need to add it manually. 








When creating an angular application , at the time of creation we will see the below screen












If you select  yes, it will automatically add the routing Model to your project.

We need to use the below 
CLI code to generate the router in Angular Application.









Configuring Routes in Angular Application

you need to configure the path and their respective component in the AppRoutingModule 













import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmployeeDetailsComponent } from '../employee-details.component';
import { DepartmentDetailsComponent } from '../department-details.component';


const routes: Routes = [
  {
    path:'employeeLink', component:EmployeeDetailsComponent
  },
  {
    path:'departmentLink', component: DepartmentDetailsComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


appModule.ts
















.html Changes














Default when loads, the below page gets displayed















On Clicking on the Department Details
























From the above HTML Code, we need to understand two important concepts i.e. routerLink and router-outlet

Router-outlet:
this is a container | placeholder with in a main page to load | display component info

or

The Router Outlet is a dynamic component that the router uses to display views based on router navigation.

So, the role of <router-outlet> is to mark where the router displays the view. This is the location where angular will insert the component.


Router Link
This will bind route path to html element[hyperlink],html element click
will load corresponding route path component into router-outlet of main page.
OR

With the help of router Link directive, you can link to routes of your application right from the HTML Template. You just need to add the directive to an HTML Element. When the user clicks on that element, angular navigates to that specified location.

note:
   routerLink is similar to href

Syntax: <a routerLink="pathname">text</a> (or) <a [routerLink]="['/pathname',para1value,..]">text</a>



Router Link (Client Side)

Example

<a [routerLink] = "['/departmentLink']">Department details</a> <br/>
<a [routerLink] = "['/employeeLink']">Employee details</a>
<div>
    <router-outlet></router-outlet>
</div>


Router Link: Server side
For your application to work with server side rendering, the element hosting directive has to be a link (anchor) element.


It is also possible to navigate to a route from code. To do so, we need angular router and this need to be done in your typescript file. 

We need to import the below import statement

import { Router } from '@angular/router';

second thing is add the below constructor

constructor(private router : Router){}


third thing is

Once we have the router, then the navigation is quite simple. Just call the navigate function or Router. This function takes an array. The first element of the array defines the route we want to navigate. The second is optional and allows us to pass a route parameter. The syntax is given below.

this.router.navigate['/departmentLink', 1234];


Example

.ts Changes

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-jsondemo',
  templateUrl: './jsondemo.component.html',
  styleUrls: ['./jsondemo.component.css']
})
export class JsondemoComponent {
  constructor(private router : Router){}
    GetDepartmentDetails()
    {
        this.router.navigate(['/departmentLink']);
    }
    GetEmployeeDetails()
    {
        this.router.navigate(['/employeeLink']);
    }
}


.html Changes

<h2>Angular Routing Example</h2>
<button (click)="GetDepartmentDetails()">Department Details</button>
<button (click)="GetEmployeeDetails()">Employee Details</button>
<div>
    <router-outlet></router-outlet>
</div>


Output


Initially when page Loads




Next Department Click










 5.routerLinkActive--this is used to apply css to active link

 6.Router class--this is used to redirect user from one component to
                 another component programmatically
                 [it is similar to response.redirect]
  syntax:
      this._router.navigate(['/pathname',..]);

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...