We use property binding to pass value from component to form element in html and event binding to pass value from html to angular component.

  1. In the below code when we use [value] to get the value from component to html
  2. The same way we use (input) to get back value on event like change of name text
  3. {{employee.Name}} is used to display the value. You can remove [value] or (input) to check the behavior.
  4. Instead of this we can use ngModule by importing FormsModule which takes care of both propery and data binding

empform.html

<form>
<input type="text" [value]="employee.Name" (input)="employee.Name=$event.target.value" />
{{employee.Name}}
</form>

EmployeeModel.ts

export class Employee {
  private _Name: String;

  constructor(name: String) {
    this._Name = name;
  }
}

EmployeeController.ts

export class AddemployeeComponent implements OnInit {
.
.
  public employee: Employee;

  constructor() {
    this.employee = new Employee('Mugilvannan');
  }
.
.
}

  1. For NgModeul to work name attribute(i.e. employeeName) is mandatory in form field.
    Otherwise the value wont be reflected on change
  2. [ngModel] is for value binding and (ngModelChange) is for event binding. Both can be grouped in to format called banana-in-a-box. [(ngModel)]
  3. For using ngModel, FormsModule should be added to app.module.ts
  4. So when to use expanded syntax of ngModel. There would be times where you want to change the text into uppercase or lowercase once it is entered into textbox or formfields. In suchcase we should call an event which does it. At that time you would use (ngModelChange) instead of [(ngModel)].

addemployee.component.html

  <form>
    <table style="border-collapse:collapse;" border="1" cellpadding="5">
      <tbody>
        <tr>
          <td>Name</td>
          <td><input type="text" name="employeeName" [ngModel]="employee.Name" (ngModelChange)="employee.Name=$event" /></td>
        </tr>
        <tr>
          <td colspan="2">
            <input type="submit" value="Add Employee" (click)="employee.Name='test'" />
          </td>
        </tr>
      </tbody>
    </table>
  </form>
  {{employee.Name}}

addemployee.component.html – Banana-in-a-Box format

.
.
<td><input type="text" name="employeeName" [(ngModel)]="employee.Name"/></td>
.
.

Modules helps in writing clean code like seperating modules for dataacces, UI and security. Each modules has a separate role of its own
like httpModule, routing module. Writing Modules in TS would create IIFE(Immediately Invoked Function Expression) in javascript file

module dataService{

}

So what is difference between class and module. Both are same except one. Classes are created in Global namespace.
However module can be either global or local.

class dataService{

}

Now lets wrap class with in module which is nothing more than namespace

module Shapes{
  export class Rectangle{

  } 

  export class Square{

  } 

  export class Triangle{

  } 
}

var objShapes:any = new Shapes.Square;

Simple Program for Logging Message using Module and Interface

interface ILoggerUtils {
    print(): void;
}

var LogLevel = {
    info: 1,
    Warn: 2,
    Error:3
}

module LogUtils {
    export class LoggerAtError implements ILoggerUtils {
        
    print(): void {
        console.log("Log Message during Error");
    }
}

export class LoggerAtInfo implements ILoggerUtils {
    print(): void {
        console.log("Log Message during Info");
    }
}

export class LoggerAtWarn implements ILoggerUtils {
    print(): void {
        console.log("Log Message during Warn");
    }
  }
}

window.onload = function () {
    var objLoggerUtil: ILoggerUtils;

    var logLevel = LogLevel.info;

    switch (logLevel) {
        case LogLevel.info:
            objLoggerUtil = new LogUtils.LoggerAtInfo();
            break;
        case LogLevel.Warn:
            objLoggerUtil = new LogUtils.LoggerAtWarn();
            break;
        case LogLevel.Error:
            objLoggerUtil = new LogUtils.LoggerAtError();
            break;
    }

    objLoggerUtil.print();
}

Output

Log Message during Info

While doing we need to let know Typescript how the datatypes are defined.The definition files are available in internet and it should be added to the script folder while doing the casting

Suppose I am doing a casting HTMLElement while accessing DOMto HTMLInputElement i should add lib.d.ts which contains the definition for DOM elements.

In the below code document.getElementById(‘Name’) returns HTMLElement which is least specific compared to HTMLInputElement.

var name = <HTMLInputElement>document.getElementById('Name');
  1. Using Interface we can have blue print of list of things which needs to be implemented
interface calculateInterest {
    accountType: String,
    interest: number,
    depAmt?: number,
    calculateInt(depositAmt: number) : number;
} 

var IntForSavings: calculateInterest = {
    accountType: "Savings",
    interest: 12,     
    depAmt : 0,
    calculateInt: function (depositAmt:number) {
        this.depAmt = depositAmt;
        return depositAmt * this.interest;
    }    
};

var IntForCurrent: calculateInterest = {
    accountType: "Current",
    interest: 5,           
    depAmt: 0,
    calculateInt: function (depositAmt: number) {
        this.depAmt = depositAmt;
        return depositAmt * this.interest;
    }
};

var IntForLoans: calculateInterest = {
    accountType: "Loan Account",
    interest: 8,
    depAmt: 0,
    calculateInt: function (depositAmt: number) {
        this.depAmt = depositAmt;
        return depositAmt * this.interest;
    }
};

console.log(IntForSavings.accountType + ' yields ' + IntForSavings.calculateInt(12000) + ' for cash amount of ' + IntForSavings.depAmt);
console.log(IntForCurrent.accountType + ' yields ' + IntForCurrent.calculateInt(6000) + ' for cash amount of ' + IntForCurrent.depAmt);
console.log(IntForLoans.accountType + ' yields ' + IntForLoans.calculateInt(3000) + ' for cash amount of ' + IntForLoans.depAmt);

Output

Savings yields 144000 for cash amount of 12000
Current yields 30000 for cash amount of 6000
Loan Account yields 24000 for cash amount of 3000

Classes extending Interface
Accounts.ts

interface Accounts {
    accountType?: string;
    calculateInterest(accountType: string): number;
}

class SavingsAcc implements Accounts {
   
    minimumBalance: number = 10000;
    accountType: string = 'Savings';    

    calculateInterest(accountType: string): number{
        return 5;
    }
}

class CurrentAcc implements Accounts {
    minimumBalance: number;
    accountType: string = 'Current';
    calculateInterest(accountType: string): number {
        return 5;
    }
}

class LoanAcc implements Accounts {
    accountType: string = 'Loan';
    calculateInterest(accountType: string): number {
        return 12;
    }
}

class Customer {
    private _accountType: Accounts;          

    constructor(customerId: number, AccountType : Accounts) {
        this._accountType = AccountType;
    }

    public get accountType(): Accounts {
        return this._accountType;
    }
    public set accountType(value: Accounts) {
        this._accountType = value;
    }
}

window.onload = function () {
    var objCustomer: Customer = new Customer(1001, new LoanAcc());    
    console.log(objCustomer.accountType.accountType + ' Account with interest rate of ' + objCustomer.accountType.calculateInterest('Loan'));


    var objCustomer: Customer = new Customer(1001, new SavingsAcc());
    console.log(objCustomer.accountType.accountType + ' Account with interest rate of ' + objCustomer.accountType.calculateInterest('Savings'));
}

Output

Loan Account with interest of 12
Savings Account with interest of 5

Accessing property of class extending Interface
We have the same code of Accounts.ts with slight modification on window.load. We try to access a property specific to class implementing interface.
In the below code minimumBalance is a property specific to savingsAccount which implements Accounts. In such case we need to do type case from generic interface object to specific class object
so the property specific to class is available.

window.onload = function () {
    var objCustomer: Customer = new Customer(1001, new SavingsAcc());
    var objSavingAcc: SavingsAcc = <SavingsAcc>objCustomer.accountType;
    console.log(objCustomer.accountType.accountType + ' Account with interest rate of ' + objCustomer.accountType.calculateInterest('Savings') + ' with minimum balance of ' + objSavingAcc.minimumBalance);
}

Output

Savings Account with interest rate of 5 with minimum balance of 10000

Using Interface to write clean code
One of the advantage of interface is while passing multiple arguments to constructor we can avoid the misplacement of the argument passed
like the one in code below. This is similar to ENUM in Java. The the Account class constructor we can change the arguments to interface as follows

Interfaces.ts

interface IPerson {
    name: string;
    age: number;
    location: string;
}

interface IEmployee extends IPerson{
    empId: number;
}

interface ICustomer extends IPerson {
    custId: number;
    accType: string;
}

Account.ts

class Account {
    private _name: string;
    private _age: number;
    private _location: string;    
    private _custId: number;   
    private _accType: string;   

    constructor(name: string, age: number, location: string, custId: number, accType: string) {    
        this._name = name;
        this._age = age;
        this._location = location;
        this._custId = custId;
        this._accType = accType;
    }
}

Refactored Account class with constructor arguments changed to inteface

Account.ts

class Account {
    private _name: string;
    private _age: number;
    private _location: string;    
    private _custId: number;   
    private _accType: string;   

    constructor(iPerson: ICustomer) {
        this._name = iPerson.name;
        this._age = iPerson.age;
        this._location = iPerson.location;
        this._custId = iPerson.custId;
        this._accType = iPerson.accType;
    }
}

Functions using arrow function Expression

var multiply = function (num: number) {
        return num * num;
}

The same above function could be written using arrow key expression as below

var multiply = (num1: number, num2: number) => return num1 * num2;

//With flower braces in case of multiple statements
var multiply = (num1: number, num2: number) => {return num1 * num2;};

we can also do function declaration and definition in two separate lines as one below

//function declaration
var multiply: (num1: number, num2: number) => number;    

//function definition
multiply = function (num1: number, num2: number) {
  return num1 * num2;
}

//function taking object literals as arguments
var multiply: (numbs: { num1: number, num2: number }) => number;    
var numbs = { num1: 2, num2: 4 };

multiply = function (numbs) {
   return numbs.num1 * numbs.num2;
}
  1. What is difference between let and var while declaring variable?
    var is Function Scoped and let is block scoped
    Using var

    var foo = 123;
    if (true) {
        var foo = 456;
    }
    
    console.log(foo); // 456
    

    Using let

    let foo = 123;
    if (true) {
        let foo = 456;
    
    }
    console.log(foo); // 123
    
  2. What would be the value of the below variables?
     
     //Value is Undefined
     var foo:string;
     
     //You can explicitly define value as undefined 
     var age = undefined;
    
     //any is a valid value which is default type until the variable assumes some data type by type inference
     var location:any;
    
     //undefined and null could be assigned to any of the datatype
     var pincode:any=undefined;
     var state:any=null;
    
  3. Why the below is not possible in interface?
    I am having a interface and class like one below which results in compile time exception

    interface test1 {
    }
    
    class test2 implements test1
    {
        public foo;
    }
    
    let test: test1 = new test2();
    
    test.foo = 'test';
    

    The reason for the compilation error is when you reference a variable with specific interface in TypeScript, you can only use the properties and methods declared in the interface of the variable
    You are assigning test1 as a type of test variable, test1 interface doesn’t have foo property in it. so that’s why you are getting this error. If you change the type to let test: test2: new test2();. it won’t throw any error like one below

    let test: test2 = new test2();
    test.foo = 'test';
    

    There are two workaround for this. One is not to define the type while initializing variable like one below

    interface test1 { }
    class test2 implements test1{
        public foo;
    }
    let test = new test2();
    test.foo = 'test';
    

    Other is to use any while initializing variable

    interface test1 { }
    class test2 implements test1{
        public foo;
    }
    let test: test1 | any = new test2();
    test.foo = 'test';
    
  1. Services are mostly used in displaying datas from APIs
  2. To generate a new service use ng generate service Services/SERVICE_NAME
  3. services are injectable because they would be mostly called by other components
  4. Injection of services can happen at three level
    • AppModule – Same Instance of Service Injected would be available across application
    • AppComponent – Same Instance of Service Injected at this level would be available in this component and all child component
    • Any Other Component – Same Instance of Service Injected would be available to this component and child component(not to parent component)
  5. @Injectable is not needed if the Service is added in app.modules.ts

aboutus.component.ts

.
.
constructor(private objApi:ApiService) { 
    this.objApi.getDataFromRest();
  }
.
.

api.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor() { }

  getDataFromRest()
  {
    return console.log("Data from Rest Method");
  }
}

If Else
aboutus.component.ts

export class AboutusComponent implements OnInit {
  showMsg: boolean = true;
  .
  .
  .
}

aboutus.component.html

<p *ngIf='showMsg; else elseBlock'>aboutus works from If block!</p>

<ng-template #elseBlock>
    <p>aboutus works from else block!</p>
</ng-template>

Output

aboutus works from If block!

Switch Case
aboutus.component.ts

export class AboutusComponent implements OnInit {
  .
  .
  color : string =  'pink';
  .
  .
}

aboutus.component.html

<div [ngSwitch] = 'color'>
    <p *ngSwitchCase="'blue'">Its Blue Color</p>
    <p *ngSwitchCase="'red'">Its Red Color</p>
    <p *ngSwitchCase="'green'">Its Green Color</p>    
    <p *ngSwitchDefault>Its Default Color</p>    
</div>

Output

Its Default Color

For Angular routing the routing option should have been enabled while starting new project.

  1. To define a link you need to use routerLink instead of href followed by route in other side of equals like one in app.component.html
      <ul>
        <li><a routerLink="/">Home</a></li>
        <li><a routerLink="/aboutus">About Us</a></li>
        <li><a routerLink="/services">Services</a></li>
        <li><a routerLink="/contactus">Contact Us</a></li>
      </ul>
    
  2. The list of routes needs to be defined in app-routing.module.ts. It is defined inside routes array list with path and component as key value pair like one below app-routing.module.ts
    const routes: Routes = [
      {path:'aboutus', component: AboutusComponent},
      {path:'services', component: ServicesComponent},
      {path:'contactus', component:ContactComponent}
    ];
    
  3. The path and one defined assigned to routerLink in html should be same. The component is the name of the component class which represent individual page of application
  4. If you are using absolute path then it would be /PATH which takes reference of component to be loaded form root url. If you are using relative path the it would be PATH (or) ../PATH (or) ../../PATH. Incase you are using relative path clicking the link of the same page from the page you are in should throw an error(Could not be verified)
  5. Navigating to link could be acheived by two ways
    • Using RouterLink in a tags
    • Using router navigate method in ts code
  6. routerLink always knows which route is currently loaded.router navigate method does not which route is presently loaded. So we always use activateRoute and pass relativeTo as parameter and pass relative URL as parameter

app-routing.module.ts

import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {AboutusComponent} from './aboutus/aboutus.component';
import {ServicesComponent} from './services/services.component';
import {ContactComponent} from './contact/contact.component';


const routes: Routes = [
  {path:'aboutus', component: AboutusComponent},
  {path:'services', component: ServicesComponent},
  {path:'contactus', component:ContactComponent}
];

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

app.component.html

<style>
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* Change the link color to #111 (black) on hover */
li a:hover {
  background-color: #111;
}

.active {
  background-color: #4CAF50;
}

li {
  border-right: 1px solid #bbb;
}

li:last-child {
  border-right: none;
}
</style>
<div class="content" role="main">
  <ul>
    <li><a routerLink="/">Home</a></li>
    <li><a routerLink="/aboutus">About Us</a></li>
    <li><a routerLink="/services">Services</a></li>
    <li><a routerLink="/contactus">Contact Us</a></li>
  </ul>
</div>
<router-outlet></router-outlet>

sun security validator exception pkix path building failed
When it Happens
While doing maven build in intellij using maven tool bar. Not the build from intellij terminal which again calls command prompt

Why it Happens
Intellij has its own security store and java internally. So while doing build in case the security certificates are missing in inbuilt security keystore would result in the above error. Intellij java certificates are found in below location.Proxy certificates are not added to intellij keystore.

Fix

  1. The below should be done by running command prompt as administrator.
  2. Locate your network’s certificate: In a browser, navigate to “URL OF REPO” and then hit F12, go to certificates/security and get the top most certificate… Export it to MyCertificate.cer (base64 encoded)
  3. Navigate to security folder in intellij
    C:\Program Files\IntelliJ IDEA Community Edition 2019.3.4\jbr\lib\security
    
  4. Copy over MyCertificate.cer into the security folder
  5. Type “keytool -keystore cacerts -importcert -alias MyCertificate -file MyCertificate.cer” without quotes.
  6. Use the default password of “changeit”
  7. When prompted to trust the certificate type “yes”.Restart Intellij and try to run maven install again from maven to make sure the jars are imported

More Notes in above
We experienced this issue when a server changed their HTTPS SSL certificate, and our older version of Java did not recognize the root certificate authority (CA).

If you can access the HTTPS URL in your browser then it is possible to update Java to recognize the root CA.

In your browser, go to the HTTPS URL that Java could not access. Click on the HTTPS certificate chain (there is lock icon in the Internet Explorer, or the domain name left of the URL in firefox) and navigate the certificate hierarchy. At the top there should be a Primary Root CA. This could be missing from your java cacerts file. Note down the Issuer and Serial Number.