ngStyle Directive

In Angular, ngStyle is a directive that allows you to dynamically set inline styles for HTML elements. It’s a handy way to apply styles conditionally or based on some properties in your component class.

Here’s how you can use ngStyle in Angular:

Template Syntax:

<div [ngStyle]="{'property': 'value', 'property2': 'value2'}">...</div>

Using Component Properties:

You can also bind styles based on properties from your component class:

<div [ngStyle]="myStyles">...</div>
export class MyComponent {
  myStyles = {
    'color': 'blue',
    'font-size': '16px'
  };
}

Conditional Styles:

<div [ngStyle]="{'background-color': isActive ? 'green' : 'red'}">...</div>

Object Syntax: in TypeScript file

export class MyComponent {
  fontSize = '14px';
  fontWeight = 'bold';
}
<div [ngStyle]="{'font-size': fontSize, 'font-weight': fontWeight}">...</div>

Using Functions:

You can also use functions to dynamically generate styles:

export class MyComponent {
  getStyles() {
    return {
      'color': this.isImportant ? 'red' : 'black',
      'font-weight': this.isImportant ? 'bold' : 'normal'
    };
  }
}
<div [ngStyle]="getStyles()">...</div>

Difference between viewChild() and ViewChildren() decorator

viewChild() Decorator:-1) we can manipulate the DOM through viewChild().
2) It manipulates the first matching element from the DOM.
like we can use only one time for same template reference variable.

viewChildren() Decorator:- 1) we can manipulate the DOM through viewChildren().
2) It manipulates the all matching element from the DOM.
like we can use multiple times (ElementRef) for same template reference variable.

Example:- Suppose, You want to change the color of the both h1 tag text.

ViewChild() Decorator provides a easy way to create and manipulate the properties and methods of a child component from a container or root component.

Step1) Now import ElementRef, ViewChild from ‘@angular/core’ in the app.component.ts file.


import { AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })

  export class AppComponent  implements OnInit, AfterViewInit{

    @ViewChild('heading')  appHeading:ElementRef | undefined;
    constructor(){
    }
  
    ngOnInit() : void{
    }
    ngAfterViewInit(){
        if( this.appHeading){
          this.appHeading.nativeElement.style.color = "green";
        }
  }
}

Step2) Now add the below code into the app.component.html file


<div class="text-align-center col-sm-6" align="center">
<h1 #heading>App Component1</h1>
<h1 #heading>App Component2 </h1>
</div>

Step3) Now, you can see the output that only first template reference variable color is changed.

ViewChildren() Decorator is used when we want to manipulate the properties of same template reference variable into multiple times.

Step1) Now import the QueryList, ViewChildren from ‘@angular/core’ and after that change the color of template reference variable through the property first and last.


import { AfterViewInit, Component, OnInit, QueryList, ViewChildren} from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })

  export class AppComponent  implements OnInit, AfterViewInit{

    @ViewChildren('heading')  appHeading!: QueryList;
    constructor(){
    }
  
    ngOnInit() : void{
    }
    ngAfterViewInit(){
        if( this.appHeading){
          this.appHeading.first.nativeElement.style.color="green";
          this.appHeading.last.nativeElement.style.color="blue";
        }
  }
}

Step2) app.component.html file has same code as already defined above.

Step3) Now, you can see the output that both template reference variable colors are changed.

Difference between Promise and Observable

Promise and Observable are used to handle the asynchronous operation.

What is Promise?

Promise is a native to a JavaScript so you have no need to install it in your code file.

What is Observable?

Observable is a part of Rxjs library so if you want to use then firstly install rxjs library after that import into your Angular ts file.


import { Observable } from 'rxjs';

Difference between Promise and Observable

Promise
1) Promise execute immediately when we create.
Example:-


const promise = new Promise(resolve =>{
      console.log("Call Promise");
    });

Output into the browser’s console

Call Promise

Observable
1) Observable is a lazy when does not start until subscribe.


 const observable = new Observable(sub => {
      console.log("observable");
});

Output into the browser’s console
No one data will be show

Promise
2) Promise emits only single value. so if you implement multiple resolve to get the value then first resolve value will be show.


  const promise = new Promise(resolve =>{
        resolve("call promise1");
        resolve("call promise2");
        resolve("call promise3");
    });

To listen the promise use then keyword.


 promise.then(result => console.log(result));

Output into the browser’s console

call promise1

Observable
2) Observable returns multiple values.


     const observable = new Observable(sub => {
         sub.next("Observable1 is working");
         sub.next("Observable2 is working");
         sub.next("Observable3 is working");
}
observable.subscribe(result=> console.log(result);

Output into the browser’s console

Observable1 is working
Observable2 is working
Observable3 is working

Promise
3) Promise can not be cancel after create.

Observable
3) Observable can be cancel by using unsubscribe() method

Promise
4) Promise does not have operator.
Observable
4) Observable has rxjs operator like map, filter etc.

Angular Form Array

What is Angular Form Array?

In Angular Reactive Forms, A Form Array is a dynamic form where form controls are added or removed to the form by the user on run time.

Why Angular Form Array need?

Normal Form in Angular Reactive Forms is a static form with a pre-defined number of fields like form controls, their initial values, and form validation rules, and give property names for each field of the form. So If we need to add dynamic fields then we need Angular Form Array.

Declare FormArray into app.componnet.ts file


import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

Bind the hotelForm in app.component.ts file
create the hotelForm and defined the fields hotel_name, hotel_phonenum and dishVarieties defined as a form Array.


 hotelForm!: FormGroup;
 ngOnInit() : void{
    this.hotelForm = this.fb.group({
      hotel_name: '',
      hotel_phonenum: '',
      dishVarieties: this.fb.array([])
    });
  }

Now, a get method dishVarieties, which returns the dishVarieties FormArray from the hotelForm


 get dishVarieties() : FormArray {
    return this.hotelForm.controls["dishVarieties"] as FormArray
  }

newDish Form Group

We created two fields under each new dish like dish_name and dish_cost. Hence we created a FormGroup with two fields. The method newDish creates a new FormGroup and returns it.


  newDish(): FormGroup {
   return this.fb.group({
     dish_name: '',
     dish_cost: '',
   })
}

Add dish dynamically

Now, we will add a new dish into the dishVarieties FormArray. Since it is an array we can use the push method to add the new dish using the the addDish() method.


addDish() {
  this.dishVarieties.push(this.newDish());
}

Note:- addDish() method returns a FormGroup. The name of the FormGroup is its Index in the FormArray.

Remove dish dynamically

Now, we will remove a dish through the removeAt method from the dishVarieties FromArray.


removeDish(i:number) {
  this.dishVarieties.removeAt(i);
}

Now, add the complete code into the app.component.html file.


<div class="text-align-center col-sm-6" align="center">
    <h2>Add Hotel Details</h2>
    <form [formGroup]="hotelForm" id="userId">
      <div class="row col-sm-12" style="padding-bottom:10px">
        <div class="col-sm-4 float-left"><label>Name:</label> </div>
        <div class="col-sm-8"><input type="text" formControlName="hotel_name" /></div>
      </div>
  
      <div class="row col-sm-12" style="padding-bottom:10px">
        <div class="col-sm-4 float-left"><label>Phone:</label> </div>
        <div class="col-sm-8"><input type="text" formControlName="hotel_phonenum" /></div>
      </div>
  
      <div formArrayName="dishVarieties">
        <div *ngFor="let dishVariety of dishVarieties.controls; let i=index">
          <div class="row col-sm-12"  style="padding-bottom:10px" [formGroupName]="i">
            <label>Dish Name :</label>
            <input type="text" formControlName="dish_name" style="width:100px;">
            <label style="padding-left:10px">Dish Cost:</label>
            <input type="text" formControlName="dish_cost"  style="width:50px;">
            <button (click)="removeDish(i)" class="btn1 btn-primary">Remove</button>
          </div>
        </div>
      </div>
  
      <div class="row col-sm-12" style="padding-bottom:10px">
        <div class="col-sm-4 float-left"></div>
        <div class="col-sm-8">
          <input type="submit" class="btn btn-primary" name="userSub" (click)="addDish()" value="Add Dish with Cost" />
        </div>
      </div>
  
      <div class="row">
       <input type="submit" class="btn btn-primary" (click)="Submit()" name="userSub" value="Submit" />
      </div>
  
    </form>
  </div>
  

Now, add the source code into the app.component.ts file


import { Component, OnInit} from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit{
  hotelForm!: FormGroup;
  constructor(private fb:FormBuilder){
  }

  ngOnInit() : void{
    this.hotelForm = this.fb.group({
      hotel_name: '',
      hotel_phonenum: '',
      dishVarieties: this.fb.array([])
    });
  }

  get dishVarieties() : FormArray {
    return this.hotelForm.controls["dishVarieties"] as FormArray
  }

  newDish(): FormGroup {
   return this.fb.group({
     dish_name: '',
     dish_cost: '',
   })
}

addDish() {
  this.dishVarieties.push(this.newDish());
}

removeDish(i:number) {
  this.dishVarieties.removeAt(i);
}

Submit(){
  console.log(this.hotelForm.value);
}
}

Now, fill the details into the form and add the Dish “Dal Makhni” and “Sahi Paneer” along with price.

After that click on the Submit button and check the output on the browser console.

Remove Dish “Dal Makhni” from the Dish items

after that click on the Submit button and check the output on the browser console.

Angular ngSwitch Directive

What is Angular ngSwitch Directive?

The ngSwitch directive is a structural directive, which is used to add or remove elements from the DOM. It works with ngSwitchcase and ngSwitchDefault directives.

Note:- Angular ngSwitch Directive is a similar to the switch statement of JavaScript.

It is used to bound the container element like div etc.

Example:- In the below example, we defined property permissionStatus into the ngSwitch and if, it exists then it will check otherwise not.


<div class="text-align-center" [ngSwitch]="permissionStatus">
</div>

ngSwitchcase

It is used to bound to an inner element, which is used inside the container element. It works like a switch case condition in JavaScript.

We use * (Asterix symbol) before the ngSwitchcase because it is a structural directive. We also assign a matchexpression like , which Angular evaluates at runtime. The Angular displays the inner element only when the value of the matchexpression matches the value of the switchexpression else it is removed from the DOM.

Example:- In the below example, we defined two ngSwitchCase which has value Allow and disallow.


<span *ngSwitchCase="'allow'">
It is accepted
</span>
<span *ngSwitchCase="'disallow'">
It is rejected
</span>

ngSwitchDefault

It works same as default in switch case condition in JavaScript. It does not have any match expression. It is also used into an inner element, which we must place inside the container element.

If no one ngSwitchCase matches in the switch expression, then the angular displays the element which is attached to the ngSwitchDefault.
Example:- In the below example, we defined ngSwitchDefault this condition will call when none of condition match in switch statement.


<span *ngSwitchDefault>
permission is not exists
</span>

complete example of ngSwitch, ngSwitchcase and ngSwitchDefault

Step1) Now put the below code into app.component.ts file and defined the permissionStatus value is allow.


import { Component, OnInit} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit{
  permissionStatus: string = 'allow';
  constructor(){
  }
  ngOnInit() : void{
  }
}

Step2) Now, put the below code into app.component.html file.


<div class="text-align-center" align="center" [ngSwitch]="permissionStatus">
    <span *ngSwitchCase="'allow'" style="color:green">
      <h2>It is accepted</h2>
      </span>
      <span *ngSwitchCase="'disallow'" style="color:red">
        <h2>It is rejected</h2>
      </span>
      <span *ngSwitchDefault>
        <h2>permission is not exists</h2>
     </span>
  </div>

Step3) When open the URL


http://localhost:4200/

Scamnerio-2
If we put the permissionStatus value disallow into the app.component.ts file.


permissionStatus: string = 'disallow';

then the output

Scamnerio-3
If we put the permissionStatus value like test into the app.component.ts file


permissionStatus: string = 'test';

then the output

Angular ngClass Directive

What is Angular ngClass Directive?

ngClass Directive is basically used to add or remove class dynamically into the angular html template file.
It supports three types of expression to represent the classes.

Types of ngClass Directive?

There are three types of ngClass.

string – the CSS classes listed in the string (space delimited) are added,
Example:-


[ngClass]="'redColor bg-color-white'"

Array – the CSS classes declared as Array elements are added,
Example:-


[ngClass]="['redColor', 'bg-color-white']"

Object – the CSS classes declared into the Object elements based on the condition.
Example:-


[ngClass]="{'redColor': colorType === 'red'}"

How to use Angular ngClass Directive?

Step1) Suppose, we create a file app.component.ts file and defined the below code.
In this file, we initialized the variable colorType and defined the value is green into it.


import { Component, OnInit} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit{
  colorType:string='green';
  constructor(){
  }

  ngOnInit() : void{
  }

}

Step2) Now we created a app.component.html file and defined the below code into it.


<div align="center" class="">
    <h1  [ngClass]="{'greenColor':colorType === 'green'}">Welcome to removeload.com</h1>
</div>

In this file, we created the ngClass and defined the condition if colorType is green then class greenColor will be added.

Step3) Now create the class greenColor into the app.component.scss file.


.greenColor{color:green;}

Step4) Now run the URL on the browser.


http://localhost:4200/

Now, you can see greenColor class is added into the h1 tag.

Suppose, if we changed the colorType variable value from green to red then condition is failed and greenColor class will not add into the h1 tag.


colorType:string='red';

Angular ngModel Directive

What is Angular ngModel Directive?

ngModel Directive is basically used to bind the form’s fields like textbox, select, textarea etc. into Angular Template Driven Form.

without ngModel directive in the Angular Template Driven Form

If we do not define ngModel directive into the form field then we are not able to get the form field value.

Suppose, you have created form into user.component.html file


<form id="" #userForm="ngForm" class="form">
    <div class="col-md-12">
        <label>User Name:-</label><input type="text" name="userName" />
    </div>
    <div class="row col-md-12"></div>
    <div class="col-md-12">
        User Age:- <input type="text" name="userAge" />
    </div>
    <div>
        <input type="submit" class="btn btn-primary" (click)="submitUserForm(userForm)" name="userSubmit"
            value="Add User" />
    </div>
  </form>

Suppose, you have created form into user.component.ts file and put the below code.


import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
  submitUserForm(userForm:NgForm){
    console.log("userFormFieldsValues",userForm.value);
  }
}

After click the submit button then we are not able to get the form field value.

Add ngModel directive in the Angular Template Driven Form

So we need to add ngModel directive to add into the form field so that we can get the form field value.


<form id="" #userForm="ngForm" class="form">
    <div class="col-md-12">
        <label>User Name:-</label><input type="text" name="userName" ngModel/>
    </div>
    <div class="row col-md-12"></div>
    <div class="col-md-12">
        User Age:- <input type="text" name="userAge" ngModel/>
    </div>
    <div>
        <input type="submit" class="btn btn-primary" (click)="submitUserForm(userForm)" name="userSubmit"
            value="Add User" />
    </div>
  </form>

Angular Behavior Subject

Angular Behavior Subject is used to pass the value from one component to other component.

Angular Behavior Subject is used to store the previous value and upcoming value in angular.

Behavior subject is used to pass the value from one component to other component through next() method.

Difference between Subject vs Behavior Subject

1) Behavior Subject is used to initialize the value while Subject you can not initialize the value.


 const behaviorSubject = new BehaviorSubject(2);

Note:- You can initialize any value like string/ number/boolean


 const subject = new Subject();

Note:- You can not initialize value.

2) Subject has upcoming value while Behavior Subject has previous and upcoming value.

There are some steps to define the difference between Subject and Behavior Subject

Step A) Suppose, you call the Subject and Behavior Subject Object value into the component comp1 then value John is showing into the Behavior Subject.

Step B) When you fill the employee value Tom into the textbox and click on the submit button then value will be show into the Subject and Behavior Subject.

Step C) Now, you click on the About Us page menu then call the about-us component and show the value of this component.

Step D) Now, you back to the Home page menu then Subject does not have value while Behavior Subject has previous value Tom.

Example:- Define the Subject and Behavior Subject through the code.

There are some steps to define the Subject and Behavior Subject code.

Step1) Firstly create the main.service.ts file and import the BehaviorSubject, Subject from the rxjs library and create the object of the Subject and BehaviorSubject and initialize the value John into the BehaviorSubject.


import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MainService {
 constructor() { }
 employeeNameBySubject = new Subject();
 employeeNameByBehaviorSubject = new BehaviorSubject('John');
}

Step2) Now, create the component comp1 and we import the main.service.ts file into the comp1.component.ts file and inject the MainService into the constructor function and call the subscribe method of the class’s subject variable employeeNameBySubject and Behavior Subject variable employeeNameByBehaviorSubject.


import { Component, OnInit } from '@angular/core';
import { MainService } from '../main.service';

@Component({
  selector: 'app-comp1',
  templateUrl: './comp1.component.html',
  styleUrls: ['./comp1.component.scss']
})
export class Comp1Component implements OnInit {

  employeeNameBySubject: string = '';
  employeeNameByBehaviorSubject: string = '';

  constructor(private _mainService : MainService) {
    this._mainService.employeeNameBySubject.subscribe(ename=>{
      this.employeeNameBySubject = ename;
    });
    this._mainService.employeeNameByBehaviorSubject.subscribe(enamebybs=>{
      this.employeeNameByBehaviorSubject = enamebybs;
    })
   }

  ngOnInit(): void {
  }

  updateEmpName(empName: { value: string; }){
    this._mainService.employeeNameBySubject.next(empName.value);
    this._mainService.employeeNameByBehaviorSubject.next(empName.value);
  }
}

Step3) Now, put the below code into the comp1.component.html file.


<div align="center" class="container">
    <div class="row align-items-center justify-content-center template-container">
      <div style="height: 10px"></div>
      <div class="row">
        <div class="col-md-6"> <h3>Subject</h3>
          <h4>Emp Name - {{ employeeNameBySubject }}</h4>
        </div>
        <div class="col-md-6"> <h3>Behavior Subject</h3>
          <h4>Emp Name - {{ employeeNameByBehaviorSubject }}</h4>
        </div>
      </div>
      <div class="row"><b>Employee Name </b>
        <input type="textbox" name="empName" #empName />
      </div>
      <div style="height: 10px"></div>
      <div class="row">
        <input class="btn btn-primary" type="button" (click)="updateEmpName(empName)" value="submit"/>
      </div>
      <div style="height: 10px"></div>
    </div>
    </div>

Note:- call the employeeNameBySubject and employeeNameByBehaviorSubject variable into the textbox, We defined the template reference variable “empName” and pass into the updateEmpName() function as a parameter.

Angular Subject

Subject is basically used to data transfer from one component to other component and both component are not related.
OR
Subject is used to data communication between two components and both component are not related.

Note:- 1) to pass the value from one component to other component through next() method.
2) Subject does not hold the last value when you change the page and come back to original page then value will be lost.
3) An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers.

How to data transfer from one component to other component?

Suppose, you have to pass employee name from component1 textbox value to component2 and component2 textbox value to component1.

there are some steps to use data transfer from one component to other component.

Step1) Firstly create the component comp1 and comp2 through the below command.


 ng g c comp1   //component1
 ng g c comp2   //component2

Step2) Include the both component into app-component.html file


<div align="center" class="container">
    <div class="col-md-12">
     
    <div class="col-md-6">
     <app-comp1></app-comp1>
   </div>
   
   <div class="col-md-6">
       <app-comp2></app-comp2>
     </div>
   
   </div>   
   </div>

Step3) Now add the below html into the comp1.component.html and comp2.component.html


<div class="row align-items-center justify-content-center" style="background-color: #daf7a6;">
    <div style="height: 10px"></div>
    <h3>Emp Name - {{ employeeName }}</h3>
    <div class="row">
      <input type="textbox" name="empName" #empName />
    </div>
    <div style="height: 10px"></div>
    <div class="row">
      <input class="btn btn-primary" type="button" (click)="updateEmpName(empName)" value="submit"/>
    </div>
    <div style="height: 10px"></div>
  </div>

Note:- In the textbox, We defined the template reference variable empName pass into the updateEmpName() function as a parameter.

Step4) Now add the below code into the component typescript file like comp1.component.ts

Firstly import Subject


import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp1',
  templateUrl: './comp1.component.html',
  styleUrls: ['./comp1.component.scss']
})
export class Comp1Component implements OnInit {
  employeeName: string = '';
  constructor() {
   }
  ngOnInit(): void {
  }
  updateEmpName(empName: { value: string; }){
    this.employeeName =empName.value;
  }
}

When you fill the employee name in the textbox of component1 and click on submit button then it will reflect only for component1 and does not reflect in component2 vice-versa.

Now, You want to data transfer from component1’s textbox value into component2

Step1) Create the main.service.ts file and import the Subject from the rxjs library.


import { Subject } from 'rxjs';

Step2) Create the object of Subject through new keyword.


 ObjectName = new Subject();

Now, add the below code into main.service.ts file


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

@Injectable({
  providedIn: 'root'
})
export class MainService {
 constructor() { }
 employeeName = new Subject();
}

Step3) import the main.service.ts file into the
comp1.component.ts file and inject the MainService into the constructor function and call the subscribe method of the class’s subject variable employeeName.

When user click the submit button then updateEmpName() method call and pass the textbox’s value through the next method.


import { Component, OnInit } from '@angular/core';
import { MainService } from '../main.service';

@Component({
  selector: 'app-comp1',
  templateUrl: './comp1.component.html',
  styleUrls: ['./comp1.component.scss']
})
export class Comp1Component implements OnInit {

  employeeName: string = '';
  constructor(private _mainService : MainService) {
    this._mainService.employeeName.subscribe(ename=>{
      this.employeeName = ename;
    })
   }

  ngOnInit(): void {
  }


  updateEmpName(empName: { value: string; }){
    this._mainService.employeeName.next(empName.value);
  }
}

Step4) Now add the comp1.component.ts file code into the comp2.component.ts

Step5) Now, run the below url on the browser.


http://localhost:4200/

Step6) you have to put textbox’s value John into the comp1 textbox then it will reflect into the comp1 component and comp2 component.

Angular Custom Pipe

Angular provides some default pipes but sometimes we need a pipe which is not exists then we create custom pipe.

How to Create Custom Pipe?

There are some steps to create custom pipe. You can create custom pipe through Angular CLI command.

Step1) Firstly create a custom pipe through angular cli commend.
Syntax:-


ng g pipe pipeName

Example:- Suppose, You create a custom pipe to check number is even or odd.


ng g pipe checkNumberEvenOdd  

When you run the above command, then two files are created.


CREATE src/app/check-number-even-odd.pipe.spec.ts (238 bytes)
CREATE src/app/check-number-even-odd.pipe.ts (241 bytes) 

Step2) pipe is automatically included into the module file.


import { CheckNumberEvenOddPipe } from './check-number-even-odd.pipe';
@NgModule({
  declarations: [
    CheckNumberEvenOddPipe
  ]

Step3) Now, implement the logic that number is even or odd in the pipe file.


import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'checkNumberEvenOdd'
})
export class CheckNumberEvenOddPipe implements PipeTransform {

  transform(value: number): string {
    if(value %2 == 0){
      return 'even';
    }else{
      return 'odd';
    }
  }
}

Step4) Now, define the variable a which is numeric into the app-component.ts file.


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  a : number = 5;
}

Step5) Now variable a pass into the template file like (app-component.html) with checkNumberEvenOdd pipe.


<div align="center">
    <h1>Check Number is Even or Odd</h1>
    <h2>{{a}} is {{a | checkNumberEvenOdd}}</h2>
</div>

Step6) Now run the URL on the browser


http://localhost:4200/

Step7) Now, get the output that when pass the number to check it is even or odd.

Angular Pipe

Angular Pipe is used to transform the input data. You can use Pipe throughout your application.

To implement the Angular Pipe use the pipe operator (|).

Angular Pipe is used into the template file like app-component.html file.

There are two types of Pipes.

Pure Pipe vs Impure Pipe

Pure Pipe:- By default pipe is pure pipe. Angular pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe.

Impure Pipe:- An impure pipe is called on every change detection cycle in Angular. You can create a impure pipe through change setting pure flag to false.


@Pipe({
  name: 'pipeName',
  pure:  false
})

There are some default Angular Pipes.

1) uppercase Pipe:- Suppose you want your input value in uppercase format then use uppercase pipe.

Syntax:-


{{ Value | uppercase}}

Example:- Suppose You have input value John and you want into uppercase format.


{{ 'John' | uppercase}}
Output:- JOHN

2) lowercase Pipe:- Suppose you want your input value in lowercase format then use lowercase pipe.

Syntax:-


{{ Value | lowercase}}

Example:- Suppose You have input value John and you want into lowercase format


{{ 'John' | lowercase}}
Output:- john

3) titlecase Pipe:- Suppose you want your input value in capitalize format then use titlecase pipe.

Syntax:-


{{ Value | titlecase}}

Example:- Suppose You have input value john and you want into capitalize format


{{ 'john' | titlecase}}
Output:- John

4) Currency Pipe:- Suppose you want to add currency with your input value then use currency pipe.

Syntax:-


{{ Value | currency:'INR':'symbol-narrow'}}

Example:- Suppose You have input value 250 and you want to add indian currency into the value.


{{ 250 | currency:'INR':'symbol-narrow'}}
Output:- ₹250.00

Angular Two Way Data Binding

Angular Two way data binding is a combination of event binding and property binding. Suppose, you want to exchange data from component to view or view to component then we use Angular Two way binding.

ngModel Directive

ngModel Directive is used to bind the Two way data binding on HTML Form elements. It binds to a form element like input, select, etc.

Syntax:-


[(ngModel)]="value"

ngModel is a part of Forms Module library so you need to import the FormsModule package into your Angular module.


import { FormsModule } from '@angular/forms';

There are some steps to implement two way data binding.

Step1) include FormsModule package into the app-module.ts file


import { FormsModule } from '@angular/forms';

Step2) create userName variable which is string datatype into the app-component.ts file


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  userName : string ='';
}

Step3) create input field which has ngModel directive which has value userName in app-component.html file


<div class="container" align="center" style="margin-top: 20px;">
    <input type="text" name="uname" [(ngModel)]="userName" />
    <br/>
    <h3>Hello {{userName}}</h3>
  </div>

Step4) Now open the localhost URL


http://localhost:4200/

Step5) Now, fill the name then get the value.

Angular Event Binding

Angular Event Binding is basically used to handle the events like click, keyup, keydown, etc and which is define into the component html file.

Event Binding is used to bind data from DOM to the component.

There are some steps to define how to use

Step1) Suppose, you define addUser method into click event and template reference variable uname in input field in app-component.html file


<div class="container" align="center" style="margin-top: 20px;">
    <div class="row">
    <label>User Name </label>
    <input type="text" name="user_name" #uname/>
    </div>
    <div class="row" style="height: 10px;"></div>
    <div class="row">
    <input type="button" class="btn btn-primary" (click)="addUser(uname.value)" value="Add User" />
    </div>
    </div>

Step2) Now define addUser() method into the app-component.ts file


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  userName : string ='';
  addUser(userName: string){
   console.log("userName:-"+userName)
  }
}

Step3) Now open the URL on the browser


http://localhost:4200/

Step4) When user file the username into textbox and click on the Add User button after that, you can get the output.

Angular Property Binding

The Property binding is used to bind HTML element property in the component html file like src, style, class, disabled etc using property binding.
Property binding enclose with square bracket []

There are some steps to define the Property Binding.

Step1) Firstly create a component property-binding


ng g c property-binding

Output will be


CREATE src/app/property-binding/property-binding.component.html (31 bytes)
CREATE src/app/property-binding/property-binding.component.spec.ts (690 bytes)
CREATE src/app/property-binding/property-binding.component.ts (315 bytes)
CREATE src/app/property-binding/property-binding.component.scss (0 bytes)
UPDATE src/app/app.module.ts (1371 bytes)

Step2) Now, open the property-binding.component.ts file and create the two variables title which is string datatype and second variable is isEnabled which is boolean datatype.


import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-property-binding',
  templateUrl: './property-binding.component.html',
  styleUrls: ['./property-binding.component.scss']
})
export class PropertyBindingComponent implements OnInit {

  title:string;
  isEnabled: boolean;
  constructor() {
    this.title= 'Property Binding Example';
    this.isEnabled = false;
   }

  ngOnInit(): void {
  }

}

Step3):- Now, open the property-binding.component.html file and add the property binding through innerText and disabled property.


<div align="center">
    <h2 [innerText]="title"></h2>
    <button class="btn btn-primary" [disabled]="!isEnabled">Details</button>
  </div>

Step4) create the route in app-routing-module.ts file
Firstly import PropertyBindingComponent


import { PropertyBindingComponent } from './property-binding/property-binding.component';

Now, create the route into the routes array.


const routes: Routes = [
  {path:'property-binding', component:PropertyBindingComponent}
];

Step5) Now open the URL on the browser


http://localhost:4200/property-binding

Step6) Now, you can see innerText and disabled property binds through property binding.

Angular String Interpolation Binding

Angular String Interpolation Binding is used to bind the data from component to the view. Basically we use string Interpolation Binding to bind the dynamic data.

Angular String Interpolation bind through the {{ }} (double curly braces) in the template file. The syntax is as shown below


{{ templateExpression }}

There are some steps to create String Interpolation Binding.

Step1) Suppose You create a component through below component


ng g c string-interpolation-binding

After run this command 4 files are created and one module file is updated.


CREATE src/app/string-interpolation-binding/string-interpolation-binding.component.html (43 bytes)
CREATE src/app/string-interpolation-binding/string-interpolation-binding.component.spec.ts (768 bytes)
CREATE src/app/string-interpolation-binding/string-interpolation-binding.component.ts (362 bytes)     
CREATE src/app/string-interpolation-binding/string-interpolation-binding.component.scss (0 bytes)     
UPDATE src/app/app.module.ts (1251 bytes)

Step2) Open the component typescript file and define the string variable userName with value John.


import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-string-interpolation-binding',
  templateUrl: './string-interpolation-binding.component.html',
  styleUrls: ['./string-interpolation-binding.component.scss']
})
export class StringInterpolationBindingComponent implements OnInit {

  userName = 'John';
  constructor() { }

  ngOnInit(): void {

  }
}

Step3) Now, open the component html file and add the below code.


Hello {{userName}}

Step4) Now, define the route into app-routing.module.ts file


import { StringInterpolationBindingComponent } from './string-interpolation-binding/string-interpolation-binding.component';
const routes: Routes = [
  {path:'string-interpolation-binding', component:StringInterpolationBindingComponent}
];

Step5) Now, open the URL


http://localhost:4200/string-interpolation-binding

Step6) Now, you can get the output

Angular Form Validations

What is Form Validation?

Form Validation is a client side validation on the browser. Form Validation is basically used to rectify that form field values are in a correct format and It is used to protect from the malicious data.

What is Angular Form Validation?

Angular Form Validation is a Client side validation. It has four predefined validations in Angular.

1) Validators.required:- this validation is used to required the form field value.
Use this into componentName.component.ts file


 this.FormName = this.fb.group({
      FieldName: ['', Validators.required]
    });
  }

Note:- where fb is a FormBuilder.

2) Validators.minLength(lengthNumber):- this validation is used to define the minimum length of the field value.


 this.FormName = this.fb.group({
      FieldName: ['', Validators.minLength(lengthNumber)]
    });
  }

3) Validators.maxLength(lengthNumber):- this validation is used to define the maximum length of the field value.


 this.FormName = this.fb.group({
      FieldName: ['', Validators.maxLength(lengthNumber)]
    });
  }

4) Validators.pattern(pattern):- this validation is used to define the pattern of the field value like define email validation etc.


 this.FormName = this.fb.group({
      FieldName: ['', Validators.pattern(pattern)]
    });
  }

Angular13 Create Custom Validation

Angular13 provides only four types of Validations but if you need any other validation then you can create custom validation. There are some steps to create the validations.

You know we have users component which is defined already.
As You know, Users Component has userAge field and we need to define minimum age limit 18 for this field, so we create a custom validation through below steps.

Step 1) Firstly create a folder which has name validators and after that we create a file in this folder, which has name custom.validators.ts file

Step 2) Now, add the below code into custom.validators.ts file.


import { AbstractControl, ValidationErrors } from '@angular/forms';
export class CustomValidators {

  public static ageGreaterThanEighteen(control: AbstractControl): ValidationErrors | null {

    if(control.value <= 18 && control.value !==''){

      return {ageGreaterThanEighteen : true}
    }

    return null;

  }
}

Note:- AbstractControl is used to control the field value.

Step 3) Add custom validation into the users.component.ts file

Step a) include custom validators class through below code.


import {CustomValidators} from '../validators/custom.validators';

Step b) Now add the custom validation into form field.


 this.userForm = this.fb.group({
      userName: ['', [Validators.required]],
      userAge: ['', [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/), CustomValidators.ageGreaterThanEighteen]]
    });

Step 4) Add custom validation into the users.component.html file


<input type="text" formControlName="userAge"  [ngClass]= "{ 'is-invalid': submitted && formData['userAge'].errors}"/>             
                <div *ngIf="submitted && formData['userAge'].errors" class="invalid-feedback">
                  <div *ngIf="formData['userAge'].errors['required']">User Age is required</div>
                  <div *ngIf="formData['userAge'].errors['pattern']">User Age must be  numeric</div>
                  <div *ngIf="formData['userAge'].errors['ageGreaterThanEighteen']">User Age must be  greater than 18</div>
                </div> 

Step 5) Now, open the URL on the browser.


http://localhost:4200/

Step 5) When user fill the age less than or equal to 18 then show validation in the userAge field.

Angular13 Reactive Form Validation

Angular 13 Reactive Form Validation is implemented into the Angular Component typescript file like componentName.component.ts file.
I have app component, so now I am creating validation for Reactive form. There are some steps to create the Validations.

1) Create Steps for app.component.ts file

Step1) Firstly import Validators from @angular/forms


import { FormBuilder, FormGroup, Validators } from '@angular/forms';

Step2) define the validation on the field name into the AppComponent class.


  userForm!: FormGroup;
  this.userForm = this.fb.group({
      userName: ['', [Validators.required]],
      userAge: ['', [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/)]]
    });

Note:- You can create multiple validation on the field, we created two validation on userAge, First Validation is used to userAge must be validate and second Validation is used to define the userAge must be numeric only.

Step3) get the form fields data.


get formData() { return this.userForm.controls; }

After, create the validation then complete app.component.ts file


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  userForm!: FormGroup;
  submitted = false;
  constructor( protected readonly fb:FormBuilder) {
  }

 get formData() {
   return this.userForm.controls;
 }

  ngOnInit(): void {
    this.setupUserForm();
  }

  setupUserForm(){
    this.userForm = this.fb.group({
      userName: ['',[Validators.required]],
      userAge:['',[Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/)]]
    })
  }

  submitUserform(){
  this.submitted = true;
  if(this.userForm.invalid){
    return;
  }
  let user_name=  this.userForm.controls['userName'].value;
  let user_age=  this.userForm.controls['userAge'].value;
  console.log("username: "+user_name);
  console.log("userage: "+user_age);  
}

}

2) Create Steps for app.component.html file

Step1) implement the validation under the validate fields like userAge through *ngIf condition.


<input type="text" formControlName="userAge"  [ngClass]= "{ 'is-invalid': submitted && formData['userAge'].errors}"/>             
<div *ngIf="submitted && formData['userAge'].errors" class="invalid-feedback">
    <div *ngIf="formData['userAge'].errors['required']">User Age is required</div>
    <div *ngIf="formData['userAge'].errors['pattern']">User Age must be  numeric</div>
</div>  

Now, complete the app.component.html file


<div class="container">
    <div class="col-md-3"></div>
        <div class="col-md-6 text-center">
          <h1>Add User</h1>
          <form id="user" [formGroup]="userForm" class="form">
            <div class="col-md-12 row">
              <div class="col-md-4">
                <label>User Name</label>
              </div>
              <div class="col-md-8">
                <input type="text" formControlName="userName" [ngClass]= "{ 'is-invalid': submitted && formData['userName'].errors}" /> 
                <div *ngIf="submitted && formData['userName'].errors" class="invalid-feedback">
                  <div *ngIf="formData['userName'].errors['required']">User Name is required</div>
                </div>         
              </div>
            </div>
            <div class="col-md-12 row" style="height: 15px"></div>
            <div class="col-md-12 row">
              <div class="col-md-4">
                <label>User Age</label>
              </div>
              <div class="col-md-8">
                <input type="text" formControlName="userAge"  [ngClass]= "{ 'is-invalid': submitted && formData['userAge'].errors}"/>             
                <div *ngIf="submitted && formData['userAge'].errors" class="invalid-feedback">
                  <div *ngIf="formData['userAge'].errors['required']">User Age is required</div>
                  <div *ngIf="formData['userAge'].errors['pattern']">User Age must be  numeric</div>
                </div>   
              </div>
            </div>
            <div class="col-md-12 row" style="height: 15px"></div>
            <div  align="center">
              <input type="submit" name="userSubmit" (click)="submitUserform()" value="Add User" />
            </div>
          </form>
        </div>
        <div class="col-md-3"></div>
      </div>

Create the css into the users.component.scss file.


.invalid-feedback{color:red;}

Now run the URL on the browser.


http://localhost:4200/users

5) When I click the submit button without fill the textbox value then show validation.

6) When I click the submit button after fill the string value into userAge textbox then show validation.

Angular Template Driven Form

Template-driven forms are simpler to use and more declarative. They rely heavily on Angular’s directives and are defined directly in the HTML template. Angular automatically creates the form model based on the directives and inputs used in the template.

Angular Template Driven Form is a old way to create the form in Angular. Most of work of Angular form is done in component html file like componentName.component.html. We define Validation logic, etc in this component.html file.
There are some steps to create the Template Driven form.

Step1) Firstly include FormsModule in app.module.ts file


import { FormsModule } from '@angular/forms';

Step2) Now, include FormsModule into imports array which is into @NgModule() object.


@NgModule({
imports: [
    FormsModule
  ]
});

Step3) Now, include NgForm from the ‘@angular/forms’ in users.component.ts file


import { NgForm } from '@angular/forms';

Step4) Now, create the html code into users.component.html file
There are some steps used to create template Driven Form.
1) formname start with # tag and equal to ngForm
2) Use ngModel is a directive and it is used to bind the fields like input field, select field, etc.


<div class="container">
    <div class="col-md-3"></div>
    <div class="col-md-6 text-center">
      <h1>Add User</h1>
      <form id="" #userForm="ngForm" (ngSubmit) = "submitUserform(userForm)" class="form">
        <div class="col-md-12 row">
          <div class="col-md-4">
            <label>User Name</label>
          </div>
          <div class="col-md-8">
            <input type="text" name="userName" ngModel/>
          </div>
        </div>
        <div class="col-md-12 row" style="height: 15px"></div>
        <div class="col-md-12 row">
          <div class="col-md-4">
            <label>User Age</label>
          </div>
          <div class="col-md-8">
            <input type="text" name="userAge" ngModel/>
          </div>
        </div>
        <div class="col-md-12 row" style="height: 15px"></div>
        <div class="col-md-12 row" align="center">
          <input type="submit" name="userSubmit"  value="Add User" />
        </div>
      </form>
    </div>
    <div class="col-md-3"></div>
  </div>
  

Step5) Now, define the code into users.component.ts file.


 export class UsersComponent implements OnInit {
  constructor() { }

  ngOnInit(): void {
  }

  submitUserform(userForm:NgForm){
     console.log("Username-",userForm.value.userName);
     console.log("Userage-",userForm.value.userAge);

    }

}

Step6) Now you can see the user form into browser.

Step7)When the user fill the details and click on the AddUser button then you can get the value into the console.

Angular Reactive Form

Reactive forms provide a more explicit and programmatic way of managing forms. They are defined in the component class, giving developers more control over form behavior, validation, and state management. Reactive forms are more suitable for complex forms and scenarios where fine-grained control is needed.

Angular Reactive Form or Angular modal driven form both are same. Reactive Form is a new way to create the form in Angular. Most of work of Angular form is done in component typescript file like componentName.component.ts. We define Business logic, Validation logic, etc in this component.ts file.
There are some steps to create the Reactive form.

Step1) Firstly include ReactiveFormsModule in app.module.ts file


import { ReactiveFormsModule } from '@angular/forms';

Step2) Now, include ReactiveFormsModule into imports array which is into @NgModule() object.


@NgModule({
imports: [
    ReactiveFormsModule
  ]
});

Step3) Now, include formbuilder, FormGroup and Validators from the ‘@angular/forms’ in users.component.ts file


import { FormBuilder, FormGroup, Validators } from '@angular/forms';

Step4) Now, create the html code into users.component.html file
There are mainly two things used to create the Reactive form.

firstly define the formName into the formGroup and defined field name into formControlName.


<div class="container">
<div class="col-md-3"></div>
    <div class="col-md-6 text-center">
      <h1>Add User</h1>
      <form id="download-vanila-form" [formGroup]="userForm" class="form">
        <div class="col-md-12 row">
          <div class="col-md-4">
            <label>User Name</label>
          </div>
          <div class="col-md-8">
            <input type="text" formControlName="userName" />
          </div>
        </div>
        <div class="col-md-12 row" style="height: 15px"></div>
        <div class="col-md-12 row">
          <div class="col-md-4">
            <label>User Age</label>
          </div>
          <div class="col-md-8">
            <input type="text" formControlName="userAge" />
          </div>
        </div>
        <div class="col-md-12 row" style="height: 15px"></div>
        <div class="col-md-12 row" align="center">
          <input type="submit" name="userSubmit" (click)="submitUserform()" value="Add User" />
        </div>
      </form>
    </div>
    <div class="col-md-3"></div>
  </div>

Step5) there are some steps to define form into the users.component.ts file.
1) Firstly, defined the formName (which is defined into users.component.html file) into the class, define the userForm into users.component.ts file.
2) Create the instance of form builder into the constructor.
3) Now, define the field name into the this.fb.group


 export class UsersComponent implements OnInit {
  public userForm!: FormGroup;
  constructor( protected readonly fb: FormBuilder) {

   }

   ngOnInit(): void {
    this.setupUserForm();
  }

  setupUserForm(){
    this.userForm = this.fb.group({
      userName: [null],
      userAge: [null]
    });
  }

  submitUserform(){
  let user_name = this.userForm.controls['userName'].value;
  let user_age = this.userForm.controls['userAge'].value;
  console.log("user_name+++",user_name);
  console.log("user_age+++",user_age);
  }

}

Step6) Now you can see the user form into browser.

Step7)When the user fill the details and click on the AddUser button then you can get the value into the console.

Angular Component

Angular Component is the main building block to create the Angular Project. It is a TypeScript class that controls a portion of the user interface (UI) and interacts with the application logic. Components are the core of Angular’s component-based architecture, enabling developers to create modular, reusable, and maintainable code. You can create components through the Angular CLI command.

Concepts of an Angular Component

1. Component Class:

The component class contains the data and logic that defines how the component behaves. This class is written in TypeScript and typically includes properties and methods that are used in the template (HTML) to bind data and handle events.

2. Component Decorator:

The @Component decorator is used to define metadata for the component, such as its selector, template, styles, and more. This decorator tells Angular that the class is a component and provides information about how it should be processed.


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

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent {
  title = 'Hello, World!';
}

Selector:

The selector is a string that identifies the component in the HTML template. It allows Angular to locate and render the component. The selector is used as a custom HTML tag within other templates.

call the component in another component HTML file


<app-hello></app-hello>

Template:

The template defines the HTML structure of the component. It can either be inline (within the @Component decorator) or in a separate file. The template can bind to the component’s properties and methods using Angular’s data binding syntax.


<h1>{{ title }}</h1>

Styles:

The styles define the appearance of the component. Like templates, styles can be included inline, in a separate file, or even globally across the entire application.


h1 {
  color: green;
}

How to create the component?


ng generate component component-name

OR


ng g c component-name

After run this command 4 files are generated and 1 file is updated.

Suppose, You create users component.


ng g c users

then 4 files are generated


CREATE src/app/users/users.component.html (20 bytes)
CREATE src/app/users/users.component.spec.ts (619 bytes)
CREATE src/app/users/users.component.ts (272 bytes)
CREATE src/app/users/users.component.scss (0 bytes)

and One module file is updated
the updated file is a module file like app.module.ts

When module file is updated then component file is included in two section.
1) imported the component file like


import { UsersComponent } from './users/users.component';

2) Added component into declaration array.


@NgModule({
  declarations: [
    AppComponent,
    UsersComponent
  ], 

Now, You changed the content into users.component.html file.


<h1>Hello users!</h1>

Create the route of the component

Suppose, You want to create route for users component. There are two step to create the route.

Step1) Firstly open the route file and import the users component.
Example:- Now you are including users component into app-routing.module.ts file


import { UsersComponent } from './users/users.component';

Step2) Now, create the route into the Routes Array.


const routes: Routes = [
  {path:'users', component:UsersComponent},
];

Now, run the URL on the browser


http://localhost:4200/users

and output will be

Angular Observable

observables works as an interface to handle the different types of asynchronous operations.

Observable is a part of rxjs. It is mainly used to handle server request and response either synchronously or asynchronously manner.
OR
HTTP module use Observable to handle the API request and response.

There are some steps to define observable.

Step1) Suppose, You created user.service.ts file and create the function getUserList() into this.


import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable, throwError} from 'rxjs';


Injectable({
 providedIn: 'root'
})

export class UserService{
// Backend API URL
public apiURL="http://localhost:9200";

constructor(private http:HttpClient){}

getUserList() : Observable<any>{
return this.http.get(any)(this.apiURL+'/user-list');
}
}

Step2) Now subscribe getUserList() method into the app component.


import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {UserService} from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

user_details:[];
 constructor(private router: Router
    public _userService:UserService) { 
      this.userListData(); 
     }
userListData(){

    return this._userService.getUserList().subscribe((res) => {
   
        if(res.status == 200) {
   
          this.user_details=res.data;
           
         }
   
       }, (err) => {
          console.log(err);
     });
   
     }

}

Observable Methods

Observable is also used to pass the value in a application through next() method.

1) next():- this method is used for pass the value into application.
2) error():- this method is used for error notification.
3) complete():- this method is used to complete notification.

Now, add the below code into component app.component.ts file


import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  observableData:any;
  constructor() { }

  ngOnInit(): void {
    const observable= new Observable((data) =>{
      data.next("Hello");
      data.next("Friends");

    });

    observable.subscribe(res =>{
        console.log(res)
       
    } );
  }

}


Now, run the code and check into console.

Output:- Hello Friends

Note:- In Observable, you can pass multiple value through next() method.

unsubscribe() method

Observable used unsubscribe() method to stop the execution.


 const observable= new Observable((observer) =>{
      observer.next("Hello");
      observer.next("Friends");
      observer.complete();
    });

   observable.unsubscribe(res =>{
        console.log('stop the execution');
    } );

  }

Angular viewChild Decorator

ViewChild() is used to access a Child Component or Directive or DOM Element into the parent component.
OR
viewChild() decorator is used to manipulate DOM elements.

There are some step to define viewChild() decorators.

How to manipulate DOM elements through viewchild() decorator?

Suppose, We want to change the color of the text from black to green color by viewChild() Decorator.

firstly add template reference variable into h1 tag into the app.component.html file


<h1 #heading>App Component</h1>

Now define the reference variable heading into the @ViewChild decorator and create the name appHeading as a ElementRef into the app.component.ts file


import { AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit, AfterViewInit{

  @ViewChild('heading') appHeading:ElementRef | undefined;
  constructor(){
  }
  ngOnInit() : void{
  }

 ngAfterViewInit(){
  // console.log("appHeading",this.appHeading);  // you can check the console value of appHeading
  if( this.appHeading){
   this.appHeading.nativeElement.style.color="green";
  }

Output will be

How to access child component into the parent component through viewchild() decorator?

Suppose, you created a child Component like ChildComponent and add the below code into the child.component.ts file. In this file we defined the one function whoAmI() which returns the value “I am a child component!”
Now add the code into this.


import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  whoAmI() {
    return 'I am a child component!';
  }

}

Step2) Now add the code into the child-component.html file.


<div align="center">
    <h1>child works!</h1>
  </div>

Step3) Now include the child component into the app-component.html file


<div align="center" class="">
    <h1>Welcome</h1>
    <input type="button" name="sub" value="Submit" (click)="showDetails()" />
    <app-child></app-child>
  </div>

Step4) Now, call the child component function into the app-component.ts file through ViewChild()


import { AfterViewInit, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit, AfterViewInit{
 
  @ViewChild('child') childComp : ChildComponent | undefined;

  constructor(){
  }
  ngOnInit() : void{
  }
  ngAfterViewInit() : void {
      console.log("childComp",this.childComp);
  }

  showDetails(){
    alert(this.childComp?.whoAmI());
  }
}

When we click the submit button then get the output

Add Class into textbox through viewChild() Decorator

Suppose, You create a user component through the below command


ng g c user

Step 1:- Firstly, create the reference variable through #keyword_name, so I have added #uname in the textbox which is in the user.component.html file.


<div class="text-center" role="main">
<h2>View child</h2>
<div class="row col-md-12">
 <div style="text-align: center; width:50%"> 
<label style="margin-right:10px;">User Name</label>
<input type="text" name="user_name" #uname/>
<input type="button" name="submit" value="submit" />
</div>
</div>    
</div>

Step 2:-Now, create a property to hold the reference variable into the user.component.ts file and you want to add the class usercls into the user_name textbox and you have to add class into ngAfterViewInit() method.

Note:- Suppose You have to add a property or change the text then You should call into ngAfterViewInit() method.


import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {

  @ViewChild('uname', {static: false})  username:ElementRef;
  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit(){
    this.username.nativeElement.classList="usercls";
  }

}

Step 3:- Now, check the output class name usercls added into user_name textbox.

Angular ng-content Directive

The ng-content directive is used for content projection. the main work is used for inserting external or dynamic content. The Parent component passes the external content into the child component.

Suppose You created an automobile component through the below command.


ng g c automobile

Now, put the code into automobile.component.html file


<div>
  <h3 class="title">Maruti</h3>
  <div>Lorem Ipsum is simply dummy</div>
  <h4 class="rank">Rank 1</h4>
</div>

Now, include automobile component into app.component.html file


<div class="text-center" role="main">
<h2>AutoMobiles Industries</h2>
<div class="row">

<div class="col-md-4">
<app-automobile></automobile>
</div>

<div class="col-md-4">
<app-automobile></automobile>
</div>

<div class="col-md-4">
<app-automobile></automobile>
</div>

</div>
</div>


Now, in the above picture, all items are the same so now we are going to create a title for each section.

instead of the title, add ng-content into the automobile.component.html file and we do add title under the app-automobile into the app.component.html file


<div>
  <ng-content></ng-content>
  <div>Lorem Ipsum is simply dummy</div>
  <h4 class="rank">Rank 1</h4>
</div>

app.component.html file


<div class="text-center" role="main">
<h2>AutoMobiles Industries</h2>
<div class="row">

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Maruti</h3>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Tata</h3>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Mahindra</h3>
</automobile>
</div>

</div>
</div>

ng-content used in more than one times in child component

Suppose, You want to add more than one ng-content into a child component then you have to make it unique through select keyword in the ng-content.

Suppose, You want to create a Rank dynamic

instead of the Rank, add ng-content into the automobile.component.html file and we do add Rank under the app-automobile into the app.component.html file


<div>
  <ng-content  select=".title"></ng-content>
  <div>Lorem Ipsum is simply dummy</div>
  <ng-content select=".rank"></ng-content>
</div>

app.component.html file


<div class="text-center" role="main">
<h2>AutoMobiles Industries</h2>
<div class="row">

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Maruti</h3>
 <h4 class="rank">Rank 1</h4>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Tata</h3>
<h4 class="rank">Rank 1</h4>
</automobile>
</div>

<div class="col-md-4">
<app-automobile>
 <h3 class="title">Mahindra</h3>
<h4 class="rank">Rank 1</h4>
</automobile>
</div>

</div>
</div>

Difference between ng-template and ng-container

ng-template

It is a Angular element directive and It is basically used with structure directive.

example:-

In component ts file


isShowData=true;

in component html file


<ng-template *ngIf="isShowData">
<div>Data is showing</div>
</ng-template>

Suppose If you do not use structure directive in ng-template then value will be show true.


<ng-template>
<div>Data is showing</div>
</ng-template>
Output:

ng-container

this directive is basically used to avoid extra div and you can implement structure directive in ng-container.


 <ng-container *ngIf="userList">
 <div class="user" *ngFor="let user of userList">
        <div class="user-detail">
            {{user | json}}
        </div>

 </ng-container>

Suppose If you do not use structure directive in ng-container then content will be show.


 <ng-container>
 <div>Data is showing</div>
 </ng-container>
Output: Data is showing

Angular Decorator

The decorator is a design pattern in the Angular. It has a core concept and used to develop a project in the Angular. every decorator starts with @. there are mainly 4 types of decorators.

1) Class Decorator
2) Property Decorator
3) Method Decorator
4) Parameter Decorator

1) Class Decorators:- the class decorators are @Component and @NgModule, both are top level decorators.


import { NgModule, Component } from '@angular/core';

@Component:- Every component has @Component decorator. When you setup the angular and create a project then root component app.component.ts file has.

In app.component.ts


         @Component({
		  selector: 'app-root',
		  templateUrl: './app.component.html',
		  styleUrls: ['./app.component.css']
		})
	

selector:- it should be unique to identify the component.
templateUrl:- It is used to define component’s html file.
styleUrls:- It is used to define component’s css file.

Note:- every component has @component decorator.

@NgModule:- Every module has also @NgModule decorator. When you setup the angular and create a project then root module app.module.ts file has @NgModule decorator. It has many important property like declaration,imports,exports,providers etc.


@NgModule({
  declarations: [component1,component2],
  imports: [Module1],
  exports: [MyModule]
  providers:[Service1, Service2]
})

declarations:- this property used to declare multiple components in the modules file.
imports:- this property is used to include other modules in your module.
exports:- this property is used when you want this module should use in another module.
providers:- It is basically used to include services and used as globally.

2) Property Decorator:- there are lots of property decorator but i am representing @input() and @output() property decorator.

@input():- this decorator is used to transfer data from parent component to child component.


import { Component, Input } from '@angular/core'; // First, import Input

export class ItemDetailComponent {

  @Input() item: string; // decorate the property with @Input()

}

Note:- to complete the @Input() Decorator information, click on the link

@Output():- this decorator is used to transfer data from child component to parent component.


import { Output, EventEmitter } from '@angular/core';
	
export class ItemOutputComponent {

@Output() newItemEvent = new EventEmitter();

}

Note:- to complete the @Output() Decorator information, click on the link

3) Method Decorator:- Method decorator is used to declare methods in the component. there are many methods decorators in the angular but I am showing @HostListener.
@HostListener:- this is used to DOM event handler that listens for key-press events.
Example:- when you reload the page then this method listen the event and you can implement logic.


import {HostListener} from '@angular/core'; 	
@Component({
  selector: 'example-component',
  template: 'Woo a component!'
})
export class ExampleComponent {
  @HostListener('window:beforeunload', ['$event'])
  onWindowClose(event: any): void {
   // Do something
  }
}

4) Parameter Decorator:- Parameter decorator is used to inject in the class constructor. it is represented through @inject(). Suppose you have to inject a chatbox in your component.



import { Component, Inject } from '@angular/core';
import { ChatBox } from '../components/chatbox';

@Component({
  selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {

   constructor(@Inject(ChatBox) private ChatBox) { }
}

Angular Directive

Angular Directive is basically a class and declare with @Directive decorator. Directives are used to add behavior to an existing DOM element.

The Angular Directive can be classified into three types:
1) Component Directive
2) Structural Directive
3) Attribute Directive

1) Component Directive:- Component decorator is also called component directive. it is basically used to details the component like which template file use, which CSS file use, and name of the component.

Example:- in the app.component.ts file


@Component({
  selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})

2) Structural Directive:- Structural directives alter layout by adding, removing, and replacing elements in DOM through *ngFor, *ngIf etc. this directive start with *
these directive is basically used in the component’s html file.

Example:-I am representing example of *ngFor Directive
Suppose you have emp_records array in the app.component.ts file and which have employee’s details.


emp_records=[{
	name:"John",
	age:35,
	sex:"Male"
},

{
	name:"Rom",
	age:30,
	sex:"Male"
},

];

Now you want to show employees details in app.component.html file


<div *ngFor="const emp of element_array">
    <div>Employee's Name:- {{emp.name}}</div>
    <div>Employee's Age:- {{emp.age}}</div>
</div>

3) Attribute Directive:- Attribute directive is used to change the appearance or behavior of the element, component or other directive. there are many Attribute directive like ngModel, ngStyle, ngSwitch and ngClass.

Example:- Suppose you have to use two-way data binding then use ngModel directive.

In the app.component.html file


<input [(ngModel)]="employeeName">
{{employeeName}}

Angular Module

An angular module is a group of components, directives, services that are related. An angular module can include another module.

the default angular module is an App module when you setup a project in angular.

What is the use of Custom Angular Module?

Custom Angular Module is also called Lazy loading modules which helps us to decrease the startup to load the application.
With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.

How to create Custom Module?

There are some step to create the Module
Step1)
you can create a custom module through below command.

Syntax:-


ng g module moduleName --routing

Example:- Suppose, you have to create static-page module.


ng g module static-page --routing

After run the command then two files will be created.

1) static-page.module.ts
2) static-page-routing.module.ts

Step2) Now, add the code into the above files.
1) static-page.module.ts:- this module file has many details like components, other modules, etc. information.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { StaticPageRoutingModule } from './static-page-routing.module';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    StaticPageRoutingModule
  ]
})
export class StaticPageModule { }

Note:-If you create components into the static-page module folder then component include into the static-page.module.ts file.

2) static-page-routing.module.ts:- this file used to define the routes.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [];

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

Note:- Now you can create route in this file.

RouterModule.forChild is used for every custom module while app module use RouterModule.forRoot.

Step3) Now, create the component into this module (static-page) folder.
Suppose, I create a about-us component into this through below command.


ng g c /static-page/about-us

Now 4 files are created and 1 module file is updated.


CREATE src/app/static-page/about-us/about-us.component.html (23 bytes)
CREATE src/app/static-page/about-us/about-us.component.spec.ts (634 bytes)
CREATE src/app/static-page/about-us/about-us.component.ts (283 bytes)
CREATE src/app/static-page/about-us/about-us.component.scss (0 bytes)
UPDATE src/app/static-page/static-page.module.ts (387 bytes)

Step4) Include module into app-routing.module.ts file


import { StaticPageModule } from './static-page/static-page.module';

After that add custom module into the routes array.


const routes: Routes = [
  {path:'static-page', loadChildren:  () => import('src/app/static-page/static-page.module').then(m => m.StaticPageModule)}
];

Now add the route into the static-page-routing.module.ts file


import { AboutUsComponent } from './about-us/about-us.component';

const routes: Routes = [
  {path:'about-us', component:AboutUsComponent,
},
];

when run the website through the below the URL


http://localhost:4200/

then load the all components which is required to start the application.

When click on the about-us URL then the custom module (static-page) load along with about-us component


http://localhost:4200/static-page/about-us

Angular Form

Angular Form is a Web Form where user enter the data and click on submit button then data is passed to business logic (means data passed to Server API or any other logic implement).

There are two types of forms in the angular.
1) Template Driven Form
2) Model-Driven Form (Reactive Form)

Template-Driven Forms:

Template-driven forms are simpler to use and more declarative. They rely heavily on Angular’s directives and are defined directly in the HTML template. Angular automatically creates the form model based on the directives and inputs used in the template.

Use Case: Ideal for simple forms where minimal code is required, such as basic contact forms or login forms.

Template Driven Form read more

Reactive Forms:

Reactive forms provide a more explicit and programmatic way of managing forms. They are defined in the component class, giving developers more control over form behavior, validation, and state management. Reactive forms are more suitable for complex forms and scenarios where fine-grained control is needed.

Use Case: Ideal for complex forms with dynamic validation, custom validators, and forms that require more control over the form state.

Reactive Form read more

Angular Route

The Angular routing is used to navigate from one view to another view.
OR
The Angular routing is used to navigate one page to another page.

@angular/router is a route library package in Angular which is include into routing module file like app-routing.module.ts file.


import { RouterModule, Routes } from '@angular/router';

How to create route in routing module file?

Suppose, You have users component which has number of users information.
So firstly include users component in routing module file.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UsersComponent } from './users/users.component';

const routes: Routes = [
  { path: 'users', component: UsersComponent }
];

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

Now, open the url on the browser


http://localhost:4200/user

Now, you can see the output

What is Router Link?

Router Link is used into the anchor tag to the navigation into the angular component view file like app-component.html


<a [routerLink]='["/users"]'>Users</a>

Note:- If you use href attribute into the anchor tag instead of routerLink then page will be load.

What is Activated Route?

Activated Route is used to access the route’s parameters.
OR
If you have routes parameters and you want to access into the component typescript file through ActivatedRoute

There are some steps to use Activated Routes.
Step1) Suppose you define route parameter user_id into the routes array into route module file like (app-routing.module.ts) file.


const routes: Routes = [
  { path: 'users/:user_id', component: UserDetailsComponent }
]

Step2) Firstly import the ActivatedRoute class into the @angular/router into the angular component file like app-component.ts file.


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

Step2) Now, Inject the ActivatedRoute class into Angular component’s class through the the constructor.


constructor(private activatedroute: ActivatedRoute) { }

Step3) Now, get the parameter user_id value into the constructor.


export class UserDetailsComponent implements OnInit {

  user_id:number | undefined;
  constructor(private activatedroute: ActivatedRoute) { 

    this.activatedroute.params.subscribe(params => {
      this.user_id = params['user_id'];
    });
  }

  ngOnInit(): void {
    alert(this.user_id);
  }

}

Step4) Now run the URL on the browser.


http://localhost:4200/users/120

Step5) Now, get the output on the browser after run the above URL.

What is Wildcard route?

Wildcard route is used to handle the invalid URL in the Angular Application.
OR
If the Angular route does not exists and you run this route then you will get the below error

Error: Cannot match any route

You can handle this situation through wildcard route which has two asterisks(**).

Suppose, You created a component like PageNotFoundComponent.

Now, add the wildcard route into app-routing.module.ts file along with component PageNotFoundComponent


import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
  { path: '**', component: PageNotFoundComponent }
]

Now, run any url, which does not exists into the routes array.


http://localhost:4200/test

Now, get the output on the browser.

Angular Service

Angular Services are used to include backend API in the Angular Project. you can create service through CLI command.
Syntax:-


ng g s serviceName

Example:- Suppose you have to create user service.


ng g s user

When the above command is run then generated two files.

1) user.service.ts
2) user.service.spec.ts

1) user.service.ts:- In this file you can include get method API, post method API, put method API, delete method API and patch method API.


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

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

  constructor() { }

// post method API   
userLogin(postData):Observable{
return this.http.post('http://abc.com'+'/login',{'email':postData.userEmail,'password':postData.userPassword})
.pipe(
   catchError(this.handleError)
  )
}

// get method API
userList():Observable{
return this.http.get('http://abc.com'+'/user-list')
.pipe(
   catchError(this.handleError)
  )
}

Note:- userLogin() and userList() methods have http://abc.com as a backend API domain.

In user.component.ts file:- Now you have to include userLogin and userList Service methods.


import { Component,ChangeDetectionStrategy,OnInit,ChangeDetectorRef } from '@angular/core';
import { FormGroup,FormBuilder, Validators } from '@angular/forms';
import { UserService } from './user.service';
import { Router,ActivatedRoute } from '@angular/router';


@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

 userlogin: FormGroup;
  user_submitted:boolean=false;
  userData:any=[];
  constructor(private fb: FormBuilder,
    private router:Router,
    public UserService:UserService
    ) { }
 
 
 ngOnInit() {  
       this.userlogin = this.fb.group({
           email: ['', [Validators.required]],
           password: ['', [Validators.required]],
      });
    }
 
 
// convenience getter for easy access to form fields
get userdata() { return this.userlogin.controls; }
 
 loginSubmit(){  
     this.user_submitted = true;
	    console.log(userlogin);  
	    if (this.userlogin.invalid) {
	     //  show validation
	       return;
	   }

   return this.UserService.userLogin(this.userlogin.value).subscribe((res) => {
     if(res.status == 200){
      this.router.navigateByUrl('/user-list');
      }else{
       console.log(res.message);
         return;
      }
  });

}

// user list

 userList(){  
  return this.UserService.userList().subscribe((res) => {
     if(res.status == 200){
        this.userData=res.data;
     }else{
        console.log(res.message);
         return;
     }
  });

}
} 

Note:- providedIn:’root’ is following the singletern service pattern so this service can be used any component of the application.

2) user.service.spec.ts:- this file is used to test the user service.


import { TestBed } from '@angular/core/testing';

import { UserService } from './admin.service';

describe('UserService', () => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: UserService = TestBed.get(UserService);
    expect(service).toBeTruthy();
  });
});

Angular Setup

When you want to setup the Angular then firstly check Nodejs should be installed. if it is not installed then install firstly through below command.

Step1

Note:- If you have already installed Nodejs then directly move to Step2.


1) sudo apt-get install curl
2) curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash –

Now, Install Nodejs


3) sudo apt-get install nodejs

After installed Nodejs, check the version


node -v
npm -v

Step2

Now, you will install Angular through the angular/CLI command.


npm install -g @angular/CLI

after installed, check the version


ng --version

Now,start to create the project

Syntax:-


ng new projectName

Example:- I am creating EmployeeManagement Project


ng new EmployeeManagement

Now, goto the EmployeeManagement directory


cd EmployeeManagement

run the command


ng serve --open

After compiled successfully, you can see the URL.

Angular Project Setup

To Setup the Angular Project, Firstly installed angular, if you have not installed kindly click on the link Angular Setup

Now create the project

Syntax:-


ng new projectName

Example:- I am creating EmployeeManagement Project


ng new EmployeeManagement

Now, go to the EmployeeManagement directory


cd EmployeeManagement

run the command


ng serve --open

After compiled successfully, you can see the URL.

Angular App Module Load

When project is load then check the step of the Module and Component load.

Step1:- Firstly index.html file load, which is in the root folder of your project.

Note:- Now, you can change title of the project from this file.


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>EmployeeManagement</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

Step2:- Now, app module is load through below code.


<app-root></app-root>

Step3:- After app module is loaded then app component will load.

Step4:- Now, you can change the text of app.component.html file according to you. Suppose you have removed old content and added new content.


<h1>Hello Employee Management Tools</h1>

Now, check the URL:- http://localhost:4200/

Create Angular Component

To create the component through the CLI command.

Syntax:-


ng g c componentName

Note:- g represents generate and c represents component.

Example:- Suppose You have to create add-employee component.


ng g c add-employee

Now show the output:-

Note:- There are 4 files are created and one file is updated.

add-employee.component.scss:- Now, you can add css in this file for the component.

add-employee.component.html:- this file is used to HTML content of component.

add-employee.component.spec.ts:- this file is used to testing the component.

add-employee.component.ts:- this file is used to business logic.

app.module.ts:- this file is updated means new component is added in this file.

Create Angular Route

to add the route, firstly open the app-routing.module.ts file.

Step1:- Now import the AddEmployeeComponent in this file.


import { AddEmployeeComponent } from './add-employee/add-employee.component';

Step2:- After that, create the route and put into the route array.


const routes: Routes = [
{path:'add-employee',component:AddEmployeeComponent},
];

Step3:- Now, add the router-outlet in the app-component.html file.


<router-outlet></router-outlet>

Step4:- After save the file then open the url http://localhost:4200/add-employee

Note:-1) Hello Employee Management Tools is coming from the app.component.html file

2) add-employee works! is coming from the add-employee.component.html file

Create Angular Form

to create the Angular form, you have to use the below step.

Step1:- Firstly import FormsModule, ReactiveFormsModule in the app.module.ts file.


import { FormsModule, ReactiveFormsModule} from '@angular/forms';

Now, include modules into imports array.


@NgModule({
imports: [
FormsModule,
ReactiveFormsModule,
]
});

Step2:- Now, add HTML content in the add-employee.component.html file, which is view on the browser.
I have created a form that has three input fields like employee first name, employee last name and employee department after that created a submit button.

Note:- I have created reactive form and used formGroup to represent the form Name, formControlName used for the form field which is bind the form field value.


<div align="center" style="width:50%">
<h4>Create Employee</h4>

<form [formGroup]=”addEmpForm” (ngSubmit)=”onEmpSubmit()” novalidate autocomplete=”off”>

<div class=”input-item”>
<input type=”text” formControlName=”empFirstName” placeholder=”Employee First Name” class=”input-bordered form-control”>

</div>

<div class=”div-gap”></div>

<div class=”input-item”>
<input type=”text” formControlName=”empLastName” placeholder=”Employee Last Name” class=”input-bordered form-control”>

</div>

<div class=”div-gap”></div>

<div class=”input-item”>
<input type=”text” formControlName=”empDepart” placeholder=”Employee Department” class=”input-bordered form-control” >

</div>

<div class=”div-gap”></div>

<div class=”gaps”></div>
<div class=”d-flex justify-content-between align-items-center”>
<button type=”submit” name=”emp_sub” class=”sub-button”>Create</button>
</div>
</form>

</div>

Step3:- Now, css content added in the add-employee.component.scss file


.input-bordered
{
border-radius: 4px;
border: 2px solid #d3e0f3;
width: 100%;
padding: 10px 15px;
line-height: 20px;
}

.div-gap{height:20px;}
.sub-button{ border-radius: 4px; background-color: blue; padding: 10px;}
.invalid-feedback{color:#ff0000}

Step4:- This file is used to implement Businees logic.

FormBuilder is used to bind the form value and you can perform any action in the onEmpSubmit() function.


import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-add-employee',
templateUrl: './add-employee.component.html',
styleUrls: ['./add-employee.component.scss']
})
export class AddEmployeeComponent implements OnInit {

addEmpForm: FormGroup;

constructor(private fb: FormBuilder){}

ngOnInit(): void {

this.addEmpForm = this.fb.group({

empFirstName: [”],
empLastName: [”],
empDepart: [”]
});
}

onEmpSubmit(){

console.log(this.addEmpForm.value);

// perform an action like hit the backend API

}

}

Note:- Now, you can see the screen, user filled the form value and click on submit button then show value into console.

Create Angular Form Validation

Basically, Angular has 4 types of validation, if you need any other validation then you can create custom validation.

1) Validators.required:- this validation is used to required for field value.
2) Validators.minLength(lengthNumber):- this validation is used to define the minimum length of the field value.
3) Validators.maxLength(lengthNumber):- this validation is used to define the maximum length of the field value.
4) Validators.pattern(pattern):- this validation is used to define the pattern of the field value like define email validation etc.

Now, start to implement the validation in the form.

Step1:- firstly open the add-employee.component.ts file and import Validators in the @angular/forms.


import { FormGroup, FormBuilder, Validators } from '@angular/forms';

Now, add the validation in the form field.


ngOnInit(): void {

this.addEmpForm = this.fb.group({

empFirstName: ['',[Validators.required]],
empLastName: ['',[Validators.required]],
empDepart: ['',[Validators.required]]
});
}

Now complete business logic in the file.


import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder,Validators } from '@angular/forms';
@Component({
selector: 'app-add-employee',
templateUrl: './add-employee.component.html',
styleUrls: ['./add-employee.component.scss']
})
export class AddEmployeeComponent implements OnInit {

addEmpForm: FormGroup;
submitted:boolean=false;
constructor(private fb: FormBuilder){}

ngOnInit(): void {

this.addEmpForm = this.fb.group({

empFirstName: ['',[Validators.required]],
empLastName: ['',[Validators.required]],
empDepart: ['',[Validators.required]]
});
}

// convenience getter for easy access to form fields
get edata() { return this.addEmpForm.controls; }

onEmpSubmit(){
this.submitted=true;
if (this.addEmpForm.invalid) {
return;
}
console.log(this.addEmpForm.value);

}

}

Step2:- Now, add the validation text in the add-employee.component.html


<div align="center" style="width:50%">
<h4>Create Employee</h4>

<form [formGroup]="addEmpForm" (ngSubmit)="onEmpSubmit()" novalidate autocomplete="off">

<div class="input-item">
<input type="text" formControlName="empFirstName" placeholder="Employee First Name" class="input-bordered form-control" [ngClass]="{ 'is-invalid': submitted && edata.empFirstName.errors }">
<div *ngIf="submitted && edata.empFirstName.errors" class="invalid-feedback">
<div *ngIf="edata.empFirstName.errors.required">First Name is required</div>

</div>
</div>

<div class="div-gap"></div>

<div class="input-item">
<input type="text" formControlName="empLastName" placeholder="Employee Last Name" class="input-bordered form-control" [ngClass]="{ 'is-invalid': submitted && edata.empLastName.errors }">
<div *ngIf="submitted && edata.empLastName.errors" class="invalid-feedback">
<div *ngIf="edata.empLastName.errors.required">Last Name is required</div>
</div>
</div>

<div class="div-gap"></div>

<div class="input-item">
<input type="text" formControlName="empDepart" placeholder="Employee Department" class="input-bordered form-control" [ngClass]="{ 'is-invalid': submitted && edata.empDepart.errors }">
<div *ngIf="submitted && edata.empDepart.errors" class="invalid-feedback">
<div *ngIf="edata.empDepart.errors.required">Department is required</div>
</div>
</div>

<div class="div-gap"></div>

<div class="gaps"></div>
<div class="d-flex justify-content-between align-items-center">
<button type="submit" name="emp_sub" class="sub-button">Create</button>
</div>
</form>

</div>

Step 3:- When you click on the submit button without filling the value then show the validation message.

Angular *ngFor Directive

Angular *ngFor Directive comes under the structure directive and it works like a for of loop. *ngFor loop is used in the Component html file file to display the data.

Syntax:-


 *ngFor="let element of elementArray"

Note:- You can declare element through let or const or var.

Implement Process:-

Step1:- Declare array variable in the app.component.ts file

Example :- Suppose you have an employees array which has employee name in the app.component.ts file


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
 
  employees:any=['John','Rom','Andrew','Mike'];
  title = 'EmployeeManagement';

}

Step2:- show the employee name in the app.component.html file through *ngFor


<h1>Employees Name</h1>
<div *ngFor="let emp_name of employees">
    <div>{{emp_name}}</div>
</div>

Step3:- Now, you show the employee names on the browser.

Angular *ngIf Directive

Angular *ngIf Directive comes under the Structure Directive and it is used to based on conditional statement. *ngIf Directive is used in the component.html file to display data or not based on the condition.

Syntax:-


 *ngIf="element"

Note:- Basically *ngIf is used to show or hide condition in the html file.

Implement Process:-

Step1:- Declare Boolean variable in the app.component.ts file

Example :- Suppose you have a showTitle Boolean variable which has value true in the app.component.ts file


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'EmployeeManagement';
  showTitle:boolean=true;
}

Step2:- Now, conditional statement implemented in the app.component.html file through *ngIf


<div *ngIf="showTitle">
    <h1>Employees Management Tools</h1>
</div>

Step3:- Now, if the condition is match then show the title otherwise not.

Note:- If you define showTitle is false then does not show data on the browser.

else condition implementation:- when you use else condition in the *ngIf Directive then should use ng-template


<div *ngIf="showTitle; else notShowTitle">
    <h1>Employees Management Tools</h1>
</div>

<ng-template #notShowTitle>
  <div>
    Title is not showing(showTitle is false)
  </div>
</ng-template>

Logical Operator

You can implement logical operator in the *ngIf directive

Not Operator:- This condition is used when you match the value false.


<div *ngIf="!showTitle">
    <h1>Employees Management Tools</h1>
</div>

meaning of this condition that showTitle is false then show content.

OR Operator:- it is basically used two Boolean variable and match any one condition is true.

Example:- if you have two Boolean variable a and b and match any one condition is true.


<div *ngIf="a || b">
    <h1>Employees Management Tools</h1>
</div>

AND Operator:- it is basically used two Boolean variable and match both condition.

Example:- If you have two Boolean variables a and b and match both conditions are true


<div *ngIf="a && b">
    <h1>Employees Management Tools</h1>
</div>

Angular @Input() Decorator

Angular @Input() Decorator is used to data transfer from parent component to the child component.

Suppose, there are two components App component is a parent component and UserList is a child component.

Now, you have to pass value of userPermission variable from “App Component” to “User Component” component.

Suppose you have to defined userPermission as a Boolean variable which has value true in the app.component.ts file.

Step1:- define userPermission in the app.component.ts file


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  userPermission:boolean=true;

}

Now add the child component selector like app-user into the parent component html file (app.component.html).


<h1>Employees Management Tools</h1>
<app-user [permission]="userPermission"></app-user>

Step2:- Now, add the @input Decorator in the child component “user” and defined the permission variable, which is used in app.component.ts file


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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
  
  @Input() permission:boolean;
  constructor() { }

  ngOnInit(): void {
  }

}

Now, Add the condition based on permission in the user.component.html file.


<div *ngIf="permission">
    User allows to show this page.
</div>

<div *ngIf="!permission">
    User does not allow to show this page.
</div>

Now, if user set userPermission variable value true then show output on the browser “User can see the details.”

if user set userPermission variable value false then show output on the browser ” You have not permission to see the records”

Angular @Output Decorator

Angular @Output() Decorator is used to data transfer from child component to the parent component.

Suppose, there are two components App component is a parent component and Skill Component is a child component.

App Component:- App component has a skills array variable which has 4 skills and Child Component (Skill Component) has a functionality to add the skill in the parent component (App Component).

Step1:- app.component.ts file


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
 
  skills:Array<any>=['Angular','Nodejs','MongoDB','MySql'];

  addSkillItem(newSkill: string) {
    this.skills.push(newSkill);
  }

}

Now add the child component selector app-skill into the parent component html file (app.component.html).


<h1>Employees IT Skills</h1>
<div *ngFor="let skill of skills">{{skill}}</div>
<app-skill (newSkillEvent)="addSkillItem($event)"></app-skill>

Explanation:- 1) Firstly, you have to show skills array value through *ngFor loop.
2) After that, include Skill Component through app-skill selector.
3) Now, add the event emitter newSkillEvent which is created in the child component.
4) Now, add the function addSkillItem which is used to add skill in the skills array.

Step2:- Now, You will create a functionality to add the @Output() Decorator in the child component Skill Component


import { Component, OnInit,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-skill',
  templateUrl: './skill.component.html',
  styleUrls: ['./skill.component.scss']
})
export class SkillComponent implements OnInit {

  @Output() newSkillEvent = new EventEmitter();

  constructor() { }

  ngOnInit(): void {
  }

  addNewSkill(skill){

    this.newSkillEvent.emit(skill);

  }

}

Explanation:- 1) Firstly import Output and EventEmitter.
2) Now create the newSkillEvent Object through EventEmitter and use @Output decorator.
3) Now, create the function addNewSkill() which is used to emit new skill into newSkillEvent Object.

Now, open the skill.component.html file and put the below code.


<p><strong>Add skill</strong></p>
<label>Add new skill: <input #newSkill></label>
<button (click)="addNewSkill(newSkill.value)">Add to parent's skills list</button>

Explanation:- 1) create the input box and use #newSkill name.
2) create a button which has click event and use function addNewSkill().

Now, if you add skill in the textbox and click the button then skill will save into parents skills array.

Angular Lifecycle

Angular call life cycle hook method when you create/modified/destroy component and directive.
there are eight angular hook methods.

constructor():- Firstly constructor calls when you load the component on DOM, constructor load on the DOM before Angular hook methods.

Angular Component Lifecycle Hooks

1. ngOnChanges()

When It’s Called: Invoked whenever an input property bound to the component changes. It runs after the constructor and before ngOnInit.

Use Case: React to changes in input properties. It receives a SimpleChanges object containing the current and previous values of the changed properties.

2. ngOnInit()

When It’s Called: Called once, after the first ngOnChanges. This is the ideal place to perform component initialization, such as fetching data from a service.

Use Case: Initialize the component, set up the component’s state, and fetch initial data.

3. ngDoCheck()

When It’s Called: Called during every change detection cycle. It allows developers to implement custom change detection logic.

Use Case: Perform manual checks on the component’s state that Angular’s built-in change detection might not catch.

4. ngAfterContentInit()

When It’s Called: Triggered once after Angular projects external content into the component’s view (i.e., after the content has been inserted via <ng-content>).

Use Case: Work with projected content once it has been initialized.

5. ngAfterContentChecked()

When It’s Called: Called after every check of the content projected into the component. It runs after ngAfterContentInit and every subsequent change detection cycle.

Use Case: Respond to changes in the projected content.

6. ngAfterViewInit()

When It’s Called: Called once after Angular initializes the component’s view and its child views.

Use Case: Perform actions related to the view or child components, such as interacting with the DOM.

7. ngAfterViewChecked()

When It’s Called: Called after every check of the component’s view and child views. It runs after ngAfterViewInit and every subsequent change detection cycle.

Use Case: Respond to changes in the view or child views.

8. ngOnDestroy()

When It’s Called: Invoked just before Angular destroys the component or directive. This is the final lifecycle hook.

Use Case: Clean up resources, unsubscribe from observables, detach event handlers, and perform other cleanup tasks to avoid memory leaks.

Angular Data Binding

Angular Data Binding is used to synchronize the data between component to the view. Data binding is used to bind the dynamically data between component to view based on the user requirements.

Basically There are Two Type of Binding in the Angular
1) One way data binding
2) Two-way data binding

One-way Data Binding:- It is used to data transfer from component to view or view to the component.

1) String Interpolation Binding:- This is a One way Data Binding. One-way data binding will bind the data from the component to the view (DOM) or from view to the component. One-way data binding is unidirectional.

in app.component.ts file


      export class AppComponent {
		 employees= {
		          name: 'John',
		          age: 35
		      };
		 
		  }

in app.component.html file


      
Employee Name : {{employees.name}}
Employee Age : {{employees.age}}

2) Property Binding:- The Property binding is used to bind HTML element property in the component html file like src, style, class, disabled etc using property binding.
Property binding enclose with square bracket []

in app-component.ts file



		export class AppComponent {
		  isEnabled: boolean = false;
		}
       

in app.component.html file


      <input type="button" name="submit"  [disabled]="!isEnabled" value="Save"/>
       

3) Event Data Binding:- Angular Event Binding is basically used to handle the events like click, keyup, keydown, etc and which is define into the component html file.

Event Binding is used to bind data from DOM to the component.
in app-component.ts file



		export class AppComponent {
		  additems() {
	         console.log('add items');
	     }
		}
      

in app.component.html file


      <h1>Add Items</h1>
      <button (click)="additems()">
     

2) Two Way Data Binding:- Two-way data binding is used, when you want to exchange data from the component to view and from view to the component.
in app-component.html file


        <div class="container">
		<input [(ngModel)]="name" />
		<br/>
		<h1>Hello {{name}}</h1>
 </div>

What is Angular

Angular is a popular open-source web application framework developed and maintained by Google. It is used to build dynamic, single-page applications (SPAs) and web apps with rich user interfaces. Angular is built on TypeScript, a superset of JavaScript, which provides static typing and other features that enhance code quality and development experience.

Key Features of Angular:

Component-Based Architecture: Angular applications are built using components, which are modular, reusable, and encapsulated pieces of the UI.

Two-Way Data Binding: Angular synchronizes the data between the model (the underlying data) and the view (the UI) in real-time, ensuring that changes in one reflect immediately in the other.

Dependency Injection: Angular has a powerful dependency injection system that makes it easy to manage and inject dependencies (services, components) into your application.

Directives: Directives are special markers in the DOM that Angular interprets and transforms into behavior. For example, *ngFor is used for looping, and *ngIf is used for conditional rendering.

Routing: Angular provides a robust routing mechanism that enables developers to define navigation paths and manage the application’s state in the URL.

Forms: Angular has strong support for building forms, including both template-driven and reactive forms, with validation and error handling features.

Testing: Angular is designed with testability in mind, providing tools like Karma and Jasmine for unit testing, and Protractor for end-to-end testing.

CLI: Angular comes with a powerful Command Line Interface (CLI) that helps in scaffolding new projects, generating components, services, and other elements, as well as managing dependencies and building the project.

Angular Versions:

There are lots of improvements in the Angular version but I am sharing some important information.

Angular 2:- Written entirely in typescript
Component-based instead of Controller
ES6 and typescript supported

Angular 4:- 1) Changes in core library
2) Lot of performance improvement is made to reduce size of AOT compiler generated code.
3) Animation features are separated from @angular/core to @angular/animation.
4) Else block in *ngIf introduced:

Angular 5:- Build optimiser:
Compiler Improvements
Improved in faster Compiler support:


ng serve --aot

Angular 6:- 1) Remove support for


<template>

tag and used


<ng-template>

2) to update the package use below command


ng update packagename

Angular 7:- major release on core framework, Angular material and CLI.

Angular 8:- Added support for SASS, make more release in core framework.

Angular 9:- Smaller bundle sizes and augmented performance.
Faster testing.
Better debugging.
Improved build times, enabling AOT on by default.

Angular 10:- Angular Package Format no longer includes ESM5 or FESM5 bundles, saving download and install time when running yarn or npm install for Angular packages and libraries.
For the compiler, name spans have been added for property reads and method calls.

Angular 11:- Automatic Inlining of Fonts
Updates on Operation Byelog
Improved Reporting and Logging
Updated Language Service Preview

Angular 12:-
1) Nullish Coalescing:- The nullish coalescing operator (??) has been helping developers write cleaner code in TypeScript classes for a while now.

Example:-


{{salary !== null && salary !== undefined ? salary : calculateSalary() }}

Becomes:


{{ salary ?? calculateSalary() }}

2) Stylish Improvements
Angular components will now support inline Sass in the styles field of the @Component decorator. Previously, Sass was only available in external resources due to the Angular compiler.
To enable this feature in your existing applications add “inlineStyleLanguage”: “scss” to angular.json

3) Running ng build now defaults to production for new v12 projects which saves teams some extra steps and helps to prevent accidental development builds in production.

Angular 13:-
1) Support for TypeScript 4.4
2) Enhancements to Angular Tests
3) 100% Ivy and No More Support for View Engine
4) Angular CLI Enhancements

Angular 14

1. Standalone Components, Directives, and Pipes (Developer Preview):

Introduced a developer preview for standalone components, allowing components to be defined without the need for an Angular module (NgModule). This simplifies the structure of Angular applications.

2. Typed Forms:

Angular 14 introduced typed reactive forms, providing stronger typing in forms, which helps catch errors at compile time and improves developer productivity.

3. Optional Injectors in Embedded Views:

This feature enables more flexible dependency injection, allowing developers to create embedded views with optional injectors.

4. Enhanced Template Diagnostics:

Improved diagnostics to catch more common template errors at compile time, like nullish coalescing (??) misuse, ensuring better type safety.

5. CLI Improvements:

Enhancements to the Angular CLI, including better debugging and build performance, especially in development mode.

Angular 15

1. Standalone API Stabilization:

Standalone components, directives, and pipes became fully stable, making it easier to build and share isolated Angular features without needing modules.

2. New Directive Composition API:

Introduced a new way to compose directives, allowing developers to create more flexible and reusable components.

3. Better Optimizations:

Further improvements to build times, bundle sizes, and performance through better tree-shaking and optimization strategies.

4. Extended Internationalization (i18n) Capabilities:

Improvements in i18n, making it easier to work with localized applications.

5. Router Enhancements:

Introduced title as a route configuration option, making it simpler to manage dynamic page titles.

Angular 16

1. Hydration Support:

Angular 16 introduced hydration, enabling server-side rendering (SSR) applications to hydrate the server-rendered content on the client side, leading to faster loading times and better SEO.

2. Signal-Based Reactivity (Developer Preview):

Introduced a developer preview of signals for reactive state management, providing a more fine-grained way to handle reactivity in Angular applications.

3. Dependency Injection Improvements:

Enhanced the Dependency Injection system with @Self and @Optional metadata, making it easier to manage hierarchical dependencies.

4. Zone.js Optional:

Angular 16 made Zone.js optional, giving developers more control over change detection strategies and enabling better performance for applications that don’t require Zone.js

5. Faster Builds:

Optimized build processes with improved incremental builds, reducing the time required to build and serve Angular applications.

Angular 17

1. Full Signals Support:

Signals, a new reactive primitive, became fully supported in Angular 17. Signals offer a more efficient and predictable way to manage reactivity in Angular applications compared to traditional observables.

2. Directive Composition API Stabilization:

Finalized the directive composition API, making it easier to compose complex UIs by reusing directives across different components.

3. Enhanced Router Features:

Introduced new router features, such as lazy-loading guards and improved preloading strategies, to enhance the performance and flexibility of Angular applications.

4. Improved SSR and Hydration:

Further improvements to server-side rendering and hydration, making Angular applications faster and more SEO-friendly.

5. Faster Builds and Development Server:

Continued focus on optimizing build times and improving the development experience with an even faster development server.

Angular 18

1. Improved Signals API:

Angular 18 is expected to refine the Signals API further, making it even more intuitive and powerful for developers to manage state in Angular applications.

2. Optional NgModules Everywhere:

Building on the work started with standalone components, Angular 18 is likely to make NgModules optional across the board, simplifying the architecture of Angular applications.

3. Performance Optimizations:

Further performance optimizations, especially around large-scale applications, with improvements to tree-shaking, lazy-loading, and bundle size reduction.

4. Advanced Tooling Support:

Enhancements to the Angular CLI and DevTools, providing better support for modern development workflows, including more granular control over build processes and debugging.

Angular Interview Questions

I am sharing top 50 Angular Interview Questions, which will help you to crack the Angular test and Interview.

Q1:- What is Angular?

Ans:- Angular is a single page client application and using HTML and Typescript.

Q2:- Advantages of Angular 2 over Angular 1?

Ans:- Angular 2 is written entirely in Typescript and meets the ECMAScript 6 specification. Angular 2 is entirely component-based. Controllers and $scope are no longer used. They have been replaced by components and directives.

Q3:- What is a component?

Ans:- Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. app component is a parent component while we create a component through command


     ng g c componentName
     

Q4:- what is Decorator?

Ans:- Decorator is a design pattern in the Angular. It has a core concept and used to develop a project in the Angular. every decorator starts with @. there are mainly 4 types of decorators.

1) Class Decorator
2) Property Decorator
3) Method Decorator
4) Parameter Decorator

readmore…

Q5:- What is the command to create a component via cli?

Ans:- ng g c “componentName”

Q6:- How to install a bootstrap module?

Ans:- npm install bootstrap –save
and include file path in the angular.json file in the style section.

Q7:- How many types of Binding are there in Angular?

Ans:- Basically, there are two types of Binding in Angular.
1) One Way Data Binding:- It is used to data transfer from component to view or view to the component.
2) Two Way Data Binding:- Two-way data binding is used, when you want to exchange data from the component to view and from view to the component.

to get the complete information click on readmore…

Q8:- What is the syntax of *ngFor?

Ans:-


	<li *ngFor="let item of items; let i = index">
        {{i}} {{item}}
        </li>
  

Q9:- Difference between for in and for of?

Ans:- for in:- This is used to get the key and value from object.

Suppose, you have employee object


	let employee = {
	   "first_name": "John",
	   "last_name": "Mathew",
	   "age": 35
	}
	

Now, you want to get employee details from the employee object.


    for(const key in employee) {
    console.log( employee[key]);
   }
   
Output:-
John
Mathew
35

for of:- this is used get the value from the array.
Suppose, you have fruits array


   let fruits=['Apple','Banana', 'Orange', 'Mango'];
   

Now, get the fruits Name.


   for(let fruit of fruits){
    console.log(fruit);
   }
   
Output:-
Apple
Banana
Orange
Mango

Q:10:- How can we talk from a template to its component?

Ans:- Through Event Binding

Q11:- How do we encapsulate Component Styles in Angular?

Ans:- we can add css file in the @component decorator or add css code into this like


     styles: ['h1 { font-weight: normal; }']
     

Q12:- Difference between css and scss?

Ans:- SCSS:- Syntactically Awesome Stylesheet is the superset of CSS.SCSS contains all the features of CSS and contains more features that are not present in CSS which makes it a good choice for developers to use it. SCSS offers variables, you can shorten your code by using variables. It is a great advantage over conventional CSS.

Example:-


$white: #ffffff;
$ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;
body{
 color: $white;
 font: $ubuntu-font;
 padding: 2rem;
}

Q13:- Explain Angular Lifecycle?

Ans:- Angular call life cycle hook method when you create/modified/destroy component and directive.
there are eight angular hook methods.
1) ngOnChanges()
2) ngOnInit()
3) ngDoCheck()
4) ngAfterContentInit()
5) ngAfterContentChecked()
6) ngAfterViewInit()
7) ngAfterViewChecked()
8) ngOnDestroy()

to read the complete details click on the readmore..

Q14:- what is a pipe and how to create a custom pipe?

Ans:- Pipe:- A pipe takes data as an input and transforms it into the desired output.
in the component html file


     <p>The John's birthday is {{ birthday | date | uppercase }}</p>
     

To create the pipe:- @Pipe decorator used with


import { Pipe, PipeTransform } from '@angular/core';

Q15:- How to pass data from a parent component to its children and vice versa?

Ans:- @Input():- this decorator is used to data transfer from parent component to child component.
@Output():- this decorator is used to data transfer from child component to parent component with the help of EventEmitter.

to get the more details in @Input() decorator click on the readmore..
to get the more details in @Output() decorator click on the readmore..

Q16:- How to create a service in Angular?

Ans:- ng g s serviceName

Q17:- How can we maintain Singleton Pattern in a Service?

Ans:- A singleton service is a service instance that is shared across components. There are two ways to make a service a singleton in Angular: Declare root for the value of the @Injectable() providedIn property. Include the service in the AppModule or in a module that is only imported by the AppModule.
First way:-


@Injectable({
  providedIn: 'root'
})

SecondWay:-
In NgModule


@NgModule({
  ...
  providers: [UserService],
  ...
})

Q18:- What is Dependency Injection in Angular?

Ans:- Dependency injection (DI) is a design pattern where objects are passed to another object to complete the tasks. In angular, service or component may require other dependent services to complete a task.
Example:- create a service and integrate it into the component.

Q19:- Difference between an observable and a promise?

Ans:- Observable:- 1) Observable emits multiple values over a time.
2) You may cancel an Observable with the unsubscribe() method
3) Observable provides a lot of efficient operators like map, foreach, filter, reduce, retry, etc.

Promise:- 1) A Promise emits a single event at the completion or failure of an async operation.
2) Promise emits a single value
3) A Promise is not lazy and promise cannot be canceled.

Q20:- What is First Operator?

Ans:- It is the operator of the RxJS library. it is used to get the first element value from the array.

Q21:- What is Take operator?

Ans:- It is the operator of the RxJS library. it is used to get the element value from the array.


        import { take } from 'rxjs/operators';
		const source = of('Mango', 'Orange', 'Banana', 'Apple', 'Pine-apple');
		//take the first emitted value then complete
		const example = source.pipe(take(1));
        
Output:- Mango

Q22:- Difference between Hot Observable and cold Observable?

Ans:- Hot Observable:- Observable is hot when the data is produced outside the Observable.


import * as Rx from "rxjs";

const random = Math.random()

const observable = Rx.Observable.create((observer) => {
    observer.next(random);
});

// subscription 1
observable.subscribe((data) => {
  console.log(data); // 0.11208711666917925 (random number)
});

// subscription 2
observable.subscribe((data) => {
   console.log(data); // 0.11208711666917925 (random number)
});

Cold Observable:- An Observable is cold when data is produced inside the Observable.


import * as Rx from "rxjs";
const observable = Rx.Observable.create((observer) => {
    observer.next(Math.random());
});

// subscription 1
observable.subscribe((data) => {
  console.log(data); // 0.24957144215097515 (random number)
});

// subscription 2
observable.subscribe((data) => {
   console.log(data); // 0.004617340049055896 (random number)
});

Q:23- What is subject in Rxjs?

Ans:- A Subject is like an Observable. The main reason to use Subjects is to multicast. An Observable by default is unicast.

Q24:- What is Behaviour Subject?

Ans:- The BehaviorSubject has the characteristic that it stores the “current” value. This means that you can always directly get the last emitted value from the BehaviorSubject.

example:- an event stream of birthdays is a Subject, but the stream of a person’s age would be a BehaviorSubject.

Q24:- What is change Detection?

Ans:- Change Detection means updating the DOM whenever data is changed. whenever any data is changed, Angular will run the change detector to update the DOM.
there are 3 methods
1) onPush Change Detection
2) Behaviour Subject
3) ChangeDetectorRef

Q25:- What do you mean by ViewEncapsulation?

Ans:- View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa.
there are 3 types of View encapsulation

1) ViewEncapsulation.None:- in ViewEncapsulation.None, the style gets moved to the DOM’s head section and is not scoped to the component. There is no Shadow DOM for the component and the component style can affect all nodes in the DOM.


import { Component, ViewEncapsulation } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent {
    title = 'parent component';
}

2) ViewEncapsulation.Native:-
1) Angular will create Shadow DOM for the component.
2) Style is scoped to the component.

in body tag:-
#shadow-root

3) ViewEncapsulation.Emulated:-

1) Angular will not create a Shadow DOM for the component.
2) The style will be scoped to the component.
3) This is the default value for encapsulation.

Q26:- What is a router outlet?

Ans:- router outlet:- You can create a named Router outlet using the name property of the router-outlet


<router-outlet  name="outlet1"></router-outlet>

Q27:- What is the interceptors?

Ans:- Interceptors are a way to do some work for every single HTTP request or response.

example:- Add a token or some custom HTTP header for all outgoing HTTP requests.

Q28:- What is the router resolve?

Ans:- The Angular 8 Router provides a resolve property that takes a route resolver and allows your application to fetch data before navigating to the route
You can create a route resolver by implementing the Resolve interface.


import { Injectable } from '@angular/core';
import { APIService } from './api.service';
import { Resolve } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve {
  constructor(private apiService: APIService) {}
   resolve() {
    return this.apiService.getItems();
  }}

Q29:- What is CORS?

Ans:- Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside.

Q30:- Types Of Request Method?

Ans:- get,post,put,delete,patch

Q31:- How do we include JS and css file in Angular?

Ans:- we can add js and CSS files in the angular.json file which is included in the scripts and styles array.

Q32:- How to apply a loader in one place and used in the entire project?

Ans:- Through Interceptor we can define add in every request.

Q33:- what is the use of angular.json file?

Ans:- It has project name, root directory as source folder (src) name which contains all the components, services, directives, pipes, the starting point of our application (index.html file), the starting point of typescript file (main.ts), style files (style.css).

Q34:- why use ng build –prod?

Ans:- ng build –prod compiles with Ahead of time compilation.
Ahead of time compilation(–aot):- The AOT compiler detects and reports template binding errors during the build step before users can see them.

Q35:- What is ForRoot and forChild in the router?

Ans:- RouterModule.forRoot() is used to handle the routing in the AppModule. It is the one that instantiates the router services. All other modules will use the RouterModule.forChild([]) for handling the routing.

Q36:- what is Angular Directive?

Ans:- Angular Directive is basically a class and declares with @Directive decorator. Directives are used to add behavior to an existing DOM element.

The Angular Directive can be classified into three types:
1) Component Directive
2) Structural Directive
3) Attribute Directive

to get the complete details of Angular Directive, click on the readmore…

Q37:- What are webSocket?

Ans:- WebSocket is the internet protocol that allows for full-duplex communication between a server and clients. the server may send data to a client without the client initiating a request. WebSockets is used for chat apps etc.

Q38:- Types of Form in Angular?

Ans:- here are two type of forms in angular
1) Template Driven Form
2) Model driven forms (Reactive Forms)

to get the complete details of Angular form, click on the readmore…

Q39:- What is the dynamic component?

Ans:- Dynamic components located in the application are not defined at build time. That means that it is not used in any angular template. Instead, the component is instantiated and placed in the application at runtime.
like angular material dropbox.

Q40:- what is rxjs?

Ans:- Reactive Extensions for JavaScript (RxJS) is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or on the server-side using Node.

Q41:- What is platform-browser in angular?

Ans:- @angular/platform-browser Supports execution of Angular apps on different supported browsers.

Q42:- What is PWA (Progressibe web App) in angular?

Ans:- your app can work without an internet connection.

Q43:- what is angular material?

Ans:- Angular Material 7 is a UI component library for Angular developers. Angular Material components help in constructing attractive, consistent, and functional web pages and web applications.

Q44:- What is a module in Angular?

Ans:- Angular Module is a group of components, directives, services that are related. An angular module can include another module.
the default angular module is an App module when you setup a project in angular. you can create a custom module through command.
to get the complete details, click on the readmore…

Q45:- What is lazy loading and why will you use it?

Ans:- Lazy loading modules help us decrease the startup to load the application. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.

Q46:- What is FormGroup and FormControl?

Ans:- It is used to create an angular reactive form. FormGroup is used with FormControl and FormArray. The role of FormGroup is to track the value and validation state of the form control.

Q47:- Angular is a Framework or platform?

Ans:- It’s both a platform and a framework. When you use it for web applications, you may call it a framework. when you develop a mobile application using any available resources like NativeScript, Cordova, Ionic, etc. and you use angular and in that term, angular is a platform.

Q48:- What is Bootstrapping?

Ans:- Bootstrapping is a technique of initializing or loading our Angular application. The Angular takes the following steps to load our first view.

Index.html loads
Angular, Third-party libraries & Application loads
Main.ts the application entry point
Root Module
Root Component
Template

Q49:- What is an NgRx store?

Ans:- Ngrx is a group of Angular libraries for reactive extensions. Ngrx/Store implements the Redux pattern using the well-known RxJS observables.

Q50:- How would I restrict access to routes?

Ans:- The trick to restricting the access to your private routes is to use canActivate property exposed by the router in Angular.
canActivate takes in a guard function where you can implement a logic that will decide whether or not to activate the route.