Saturday, September 23, 2023

Angular Folder Structure with Detail Explanation and how to start Angular Application

e2e:  It comprises of end to end configuration for application that defines functionality and behavior from development to production.

End-to-end testing is referred to as e2e. This is used to evaluate user behavior after your application is installed on a production server, not to test the logic of your program (it is not for unit testing). 

This implies that it will keep track of who views your application, which people log in to it, how long they stay there, how many pages they visit while using it, when they log out, etc.

Node_Modules: It contains the repository  of all packages that ar installed for our application.

angular.json file:
This is one of the most important files and it contains all the configuration of your Angular Project. It contains the configurations such as what is the project name, what is the root directory as source folder (src) name which contains all the components, services, directives, pipes, what is the starting point of your angular application (index.html file), What is the starting point of typescript file (main.ts), etc

src: It comprises of application resources and configuration.

That means this is the place where we need to put all our application source code. So, every component, service class, modules, everything we need to put in this folder only. Whenever we create an angular project, by default the angular framework creates lots of files folder within the src folder 

.editor config: It defines configuration for current editor(vs code, vs, native for editor)

.git ignore: it specifies the configuration for connecting with git into repository.

angular.json: It contains the configuration for our application with includes global styles  and script resources etc.

                                                   
     "schematics": {                                          |writting
        "@schematics/angular:component": {<-------------------
          "inlineStyle": true,            ----------------> ng generate component demo
          "skipTests": true                 reading         [democomponent with 2 files
        },                                                              without css and spec.ts]
         ...                                                                    @Component({
        "prefix":"app"---------------------------------------> selector:'app-demo',..})
         ...
      "build":{
             ...
        "options":{
            "outputPath": "dist/app1",  -->specify location to place build files
            "index": "src/index.html",  -->specify webpage to link angular app js files
            "main": "src/main.ts",      -->specify main startup filename
            "polyfills": "src/polyfills.ts",-->specify polyfill filename
            "tsConfig": "tsconfig.app.json",
            "assets": [                    -->specify project assets location,default is
              "src/favicon.ico",              assets 
              "src/assets"                    [project assets-->images,videos,pdfs,..]
            ],
            "styles": [                    -->specify global css files path,default comes
              "src/styles.css"                with styles.css,this css will be applied to
            ],                                all the components through out the project

package.json: it comprises of configuration for packages that are required for your application.

This will describe angular project with name, description, version, node packages info and scripts
  
scripts allows running cli commands using "npm" tool, this can be used to customize cli commands

Example

Make the below changes in the package.json













Now, once you click on npm start it will run with the port Number 6000



 2.package-lock.json
         this will contain angular project node packages dependent
         packages info

 3.readme.md
         this file will contain project documentation

tsconfig.json: It comprises of typescript configuration that specifies the target ES Script, current typescript version , etc

tslint.json : It  defines the rules of typescript language.

index.html: It is the application start up page.

This HTML file contains HTML code with the head and body section. It is the starting point of your application or you can say that this is where our angular app bootstraps. If you open it you will find that there are no references to any stylesheet (CSS) nor JS files this is because all dependencies are injected during the build process.

favicon.ico: it is the shortcut icon for pages.

main.ts: It contains the configuration for libraries that are landed on application start up.

This is the entry point for our angular application. If you ever worked with programming languages like Java or C or C#, then you can compare this with the main() method of such application.

environment: it comprises of code that is used to test the environment from development to production.

BrowserList: It configures the list of supported Browsers.

assets: It comprises of non dynamic files used by your application that is Images/pdf/txt.etc

karmaconfig.js: It configures the testing framework for your application which is karma-jasmine.

browserslist:

 This will contain list of browsers which can run angular app

app Folder

Whenever you want to create any component, service, or module, you need to create it within this app folder. As you can see, by default it creates one component (app.component.ts) and one module (app.module.ts) and an angular application should have at least one component and one module.

.gitignore file
    This will contain filenames and folder names of a project to be 
        ignored | skipped, while pushing project to git hub.
Example

    development system
          |                                                                              github[internet]
       project1  --------------->  git push------------->                 repository
          package.json                 [it will read                               package.json 
           ..                                  gitignore file,              ...
          node_modules folder      node_modules folder                            |
                node packages        will not be pushed]     another developer will pull[download]
                                                                                     project into local system
          gitignore                                                                                 |
              /node_modules                                                             project1
                                                                                            package.json
                                                                                                   ...
                                                                                         project1>npm install
                                                                                                >ng s -o

appModule.ts 

It is the start up Module in application that comprises of metadata , which specifies the information about the components, modules and services used in the application.

The metadata is defined by using 

@NgModule --> Directive which comprises of following details

declarations: it declares the component to be used in application

Imports: It declares the modules to be used in the application

Providers: It declares the services to be used in the application.

bootstrap: It defines the start up component.

Note: 

Bootstrapping is the process of converting static DOM into dynamic DOM.

Syntax:

@NgModule ( {

declarations: [],

imports: [],

providers: [],

bootstrap: []

});


To Start Angular Application

ng s --open

Note:


serve option
-------------
This will build and host | run angular application with "Angular Live Development Server" with the port 4200

This will generate temporary production build files[vendor.js,main.js,..],once server is stopped all the build files will be erased, cntrl+c will stop server
   >ng serve
      ..
    cntrl c  [it will stop angular live development server and build files will be erased]

Syntax

 ng serve[s]  <options>

  1.ng serve--this will run angular app

  2.ng serve --open --this will run angular app and browser will be opened       automatically to show the output

  app1>ng serve --open

 3 ng serve --port <number>
         this will run angular app with the specified port number

    Example:
      app1>ng serve --port 5000

      goto browser
        http://localhost:5000
          ... 

          >ng serve  --port 0
             ..

      goto browser
         http://localhost:64755
              ...
*--port 0 will pick port number randomly not in use

    >ng serve --port 0 --open


Angular Example with Constructors and Installation

Step 1. Install NodeJS

Follow the link - https://nodejs.org/en/download/

Download the node.js installer for Windows and install it.






To check the installed version of Node.js, open the command prompt.


Step 2. Install TypeScript

“npm install -g typescript” and run it on command prompt

Step 3     Angular

First , we need to install Angular CLI with the below Command

npm install -g @angular/cli

Type “ng new angularProject2” and hit enter to create the angularProject2 app.

Now, we need to create a component







Now, add three images in the assets folder.

Now once the component is created, the below folder structure you will be able to see














Create one folder with the name Prods as shown below















Inside the Prods folder, we need to create a new typescript file with the name Prod.ts


export class Prods {
    public Name;
    public Price;
    public Photo;
    constructor(name: string,price: number,photo: string)
    {
        this.Name=name;
        this.Price=price;
        this.Photo=photo;
    }
}


Now, inside the productscomponent.ts , write the below code

import { Component } from '@angular/core';
import { Prods } from 'src/Prods/Prods';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent {
public Product: Prods[] =[
  new Prods('Samsung', 122,'assets\\Samsung.jpg'),
  new Prods('Sony', 1252,'assets\\Sony.jpg'),
  new Prods('Iphone', 1232,'assets\\Iphone.jpg'),
  new Prods('OnePlus', 1822,'assets\\OnePlus.jpg')
];
public categories= ['Electronics', 'Mobiles'];
}

make the below changes to the products.html file

<h3>Categories List </h3>
<ol>
    <li *ngFor ="let item of categories" >
        <span [innerHtml]="item" > </span>
    </li>
</ol>
 <table>
    <th> Name </th>
    <th> Price </th>
    <th> Preview </th>
    <tr *ngFor="let products of Product">
    <td [innerHtml]="products.Name" ></td>
    <td [innerHtml]="products.Price" ></td>
    <td> <img [src]="products.Photo" width="100" height="100" > </td>
    </tr>
</table>

appmodule.ts file changes













Next, go to index.html page, and make the below changes










Output



Thursday, September 21, 2023

Functions In Typescript Part 10

Functions is a method that defines specific action for an object.

Functions are building blocks in an application to define functionalities.

Functions are defined for handling code reusability and maintability.

The process of extracting a set of statements into the function is known as refraction.

Syntax:

function identifier(params)--> Formal Params

{

definition

}

function call;

identiifer(params);


Parameter Less Function:

A function signature can be defined without parameters so that you can access the function to reuse the set of statements defined.

A parameterless function handle specific functionality every time that returns same set of output.

Syntax:

function Hello()

{

Console.log("Welcome")

}

Hello();


Parameterized Function:

Syntax

function Hello(msg:string)

{

console.log(msg);

}

Hello("typescript");

Hello("angular");

The parameter that are defined in function signature are known as formal parameters.

The parameters values that are passed in function call are known as actual parameters.


Optional Parameters

Every function defined in a function is a mandatory, i.e you have to assign a value in a function call, you can configure optional parameters by using  null reference character.

*optional parameter can be declared in 2 ways

 1.using initialization
   syntax:
      <methodname>(para1,para2=value)
      { .. }                 |
                          optional

 2.using ? symbol
    syntax:
       <methodname>(para1,para2?:<type>)
        { .. }              |
                          optional 

Ex:

function printName(fname: string, lname ?:string)

{

if(!lname)

{

console.log("fname + " " +lname);

}

else

{

console.log(fname);

}

}


Example:


requirement:
------------
          emp class
             |
          empno
          ename----non static fields
          sal
          count---static field
 
          constructor(--){}
          incrsal(amt=2000){} --method with optional para
          display(){}
          getempscount()     --static method
          { return count }




Output



Array Parameters: A  function can be defined a single parameter that can handle multiple value. It is an Array Any Type Parameters.

The value into a function can be passed dynamically allocating array type memory.

Example:

function PrintList(list :string[])

{

for(var i=0;i<list.length;i++) {

console.log(list[i]); }

}

let name:string[] =["John", "David"];

PrintList(name);

PrintList(new Array("Delhi", "Hyd"));


Generic Type Function

The term generic represent type safe.

Generic Type is Type Safe, but handles strongly typed values.

The value type will be determined dynamically.

Syntax:

function Identifier<Type> (param:T) {

//statements

}

The generic type variables cannot be used over any type of operators as data type is not determined.

Example 

function Sum(a, b)

{

return a+b;

}

function Print<T>(a:T, b: T)

{

console.log("Addition= " + sum(a,b));

}

Print<number>(10,30)


Function Default Parameters

A function can be defined with parameters specified with default values they are automatically designated as optional parameters.

The default parameters can access the value initialized and use in the function call.

You can override the default parameter values.

function Print(id:number,name:string,price:number=4500.56) {

console.log("id="  + id + "\n " + "Name= " +name +  "\n" + "Price= " +price);

}

Print(1,"TV");

Print(2,"Mobile",1200);


Anonyonous Function

It is mostly used in the Ajax Call back functions.

Is a method without identifier.

It is mostly used in the function closure for callback.

A callback function automatically executes according to the Promise.

You can dynamically create a function and load into memory reference so that you can access by the reference name.

Example

var obj=function(msg)  {

console.log(msg);

}

obj("Welcome");

An anonymous function can also include parameter types and return type.

Example
let Sum = function(x: number, y: number) : number
{
    return x + y;
}

Sum(2,3); // returns 5


Function Recurssion

It is the process of executing the function within the function definition.

Recursion is used to handle batch Jobs.

A batch job continously executes set of statements until it encounter termination criteria.

Example

function fact(n:number)

if(n<=0) {

return 1;

}

else 

{

return (n*(fact(n-1)));

}

console.log(fact(5));


TypeScript - Arrow Functions

They are used for anonymous functions i.e for function expressions. They are also called lambda functions in other languages.



Using fat arrow =>, we dropped the need to use the function keyword. Parameters are passed in the parenthesis (), and the function expression is enclosed within the curly brackets { }.

let sum = (x: number, y: number): number => {
    return x + y;
}

sum(11, 20);


Polymorphism in Typescript Part -9

 It is the characteristics of OOPS.

 The term poly means many and morphos means forms

It defines a feature that allows the component to have multiple behaviour.

Technically it is possible by allocating different types of memory for single component

Polymorphism is configuring single base class object that can use the memory of multiple derived class.


Example

class Employee
{
    public fname:string="Pawan";
    public lname:string="Kalyan";
    public print():void {
        console.log(this.fname+ "" + this.lname);
    }
}
class PartTimeEmployee extends Employee
{
    public print():void {
        this.fname="Raj";
        this.lname="Kumar";
        console.log(this.fname+ "" + this.lname);
    }
}
class FullTimeEmployee extends Employee
{
    public print():void {
        this.fname="Kiran";
        this.lname="Kumar";
        console.log(this.fname+ "" + this.lname);
    }
}
let employee=new Array();
employee[0]=new Employee();
employee[1]= new PartTimeEmployee();
employee[2]=new FullTimeEmployee();
for(var i=0;i<employee.length;i++) {
    employee[i].print();
}

Function Overloads


In TypeScript, you can create multiple functions with the same name but different parameter types and return types. But, the number of parameters should be exactly the same, only the data type can differ.

function add(a: number, b: number): number;

function add(a: string, b: string): string;


function add(a: any, b: any): any {
    let n= a + b;
    console.log(n);
}
add(5, 20);
add('Hello', 'CodingNinjas');

Output
25


Function overloading with different number of parameters and types with same name is not supported.

function display(a:string, b:string):void //Compiler Error: Duplicate function implementation
{
    console.log(a + b);
}

function display(a:number): void //Compiler Error: Duplicate function implementation
{
    console.log(a);
}

Method overriding:
------------------
derv class redeclaring base class method with the same signature is called "method overriding"

OR

derv class method name and signature is same as base class method is called
"method overriding"


Example

class person
{
    constructor(private name:string,private age:number)
    {}
    display()
    { console.log("name:"+this.name+" age:"+this.age);}
}
//derv class
class customer extends person
{
    private custid:string;
    constructor(custid:string,name:string,age:number)
    {
        super(name,age);//initializing base object
        this.custid=custid;
    }
    display()
    {
        console.log("custid:"+this.custid);
        super.display();//calling base method to display name and age
    }
}
let cobj=new customer("c001","raju",20);
cobj.display();


Output
PS C:\Examples> tsc.cmd methodoveriding.ts PS C:\Examples> node methodoveriding custid:c001 name:raju age:20


Note:
note:
-----

*Attaching access specifier to constructor paras will generate class fields
with the same name as paras and assigning paras to class fields will be
done automatically, this will reduce lot of coding to developer.

class person class person
{ {
constructor private name:string;
(private name:string, =====> private age:number;
private age:number) constructor(name:string,age:number)
{} {
this.name=name;
.. this.age=age;
} }
...
}



Kubernetes

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