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

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

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. You can create components through the Angular CLI command.

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 for 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

Php Install

There are many ways to install PHP on your computer machine.

Install PHP through Xampp software

Xampp is a Windows,MacOs and Linux web development environment. It is the most famous in the market. when you install this software then many software is installed automatically like PHP, Apache, MariaDB, and Perl.
kindly go to the below URL to install the package

https://www.apachefriends.org/download.html

Install PHP through Wamp software

WampServer is a Windows web development environment. It allows you to create web applications with Apache2, PHP, and MySQL. You can download it through the below link.

https://www.wampserver.com/en/

Install package one by one separately

Install packages through a command in Linux.

Install Apache


sudo apt update
sudo apt install apache2

Install PHP


sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql

Install MySql


sudo apt-get install mysql-server

PHP Editor

You can try the code on the editor.


<!DOCTYPE html>
<html>
<head>
<title>PHP Editor</title>
</head>
<body>
<h1>Welcome PHP Editor</h1>
<?php 
$msg='PHP code must be write into php tag and click on the "Run" button to view the result.';
echo $msg;
?>
</body>
</html>

Try Php Editor

Php Syntax

Php is a scripting language and it is used to create dynamic webpages. It is very easy to learn. Now times more than 70% of websites are built in PHP. every PHP file has .php extension.

Syntax:-


<?php 

?>

Example:- you have to print Hello Php


<?php 
print 'Hello Php';
?>
Hello Php

Try it on PHP Editor

HTML Embedding in php file

You can embedded html code into PHP file


<HTML>
<HEAD> 
This is a sample. 
</HEAD>
<BODY>
Hello Removeload.com
<?php 
print "Hi, how are you?";
?>
</BODY>
</HTML>

How to enable PHP short tag?

You can enable php short tag through php.ini file. firstly open the php.ini file after that short_open_tag=on.


short_open_tag=on

Now, write the PHP code

Syntax:-


<?

?>

Example:- you have to print Hello Friends


<?
print 'Hello Friends';
?>
Hello Friends

Php foreach loop

foreach loop an easy way to iterate over arrays.It is used only on arrays and objects to iterate the value.

Syntax:- this syntax represent only each iteration value.


foreach (iterable_expression as $value)
 statement

Example:-
Suppose, You have game_arr variable which has 4 game and now iterate the game through foreach loop.


<?php
$game_arr=array('Hockey','Cricket','Tennis','Football');
foreach($game_arr as $game_name){

	echo $game_name.'<br/>';
}
?>
Hockey
Cricket
Tennis
Football

Try it Yourself

Syntax:- this syntax represent current element’s key to the $key variable on each iteration.


foreach (iterable_expression as $key => $value)
    statement

Example:-
Suppose, You have game_arr variable which has 4 game and now iterate the game through foreach loop.


<?php
$game=array('Hockey','Cricket','Tennis','Football');
foreach($game as $key => $game_name){

	echo $game_name.' is on array position '.$key.'<br/>';;
}
?>
Hockey is on array position 0
Cricket is on array position 1
Tennis is on array position 2
Football is on array position 3

Try it Yourself

Php do while loop

Do While loop works same as other programming languages. In the Do while loop, The only difference is that a “do while” loop checks its truth expression before ending each iteration. Basically, this kind of loop makes sure that your statement will run at least once, regardless of the truth expression’s value.

Syntax:-


do
statement
while
(expression);

Example:-


<?php
$x=1;
do{
print $x.'<br/>';
$x++;
} while($x<5)

?>
1
2
3
4

Try it Yourself

Php While loop

While loop works same the other programming language. In the while loop, If the expression’s result is true, the loop will run all the statements inside it. If the result is false, however, the loop will end and pass the program control to the statements after it.

Syntax:-


while (expression)
statement

Example:-


<?php
$i=1;
while($i<5){

	print $i."<br/>";
	$i++;
}
?>
1
2
3
4

Try it Yourself

Php for loop

The “for” loop of PHP is similar to that of the C language. It has three parameters. first parameter is used to intilize the variable value, second parameter is used to define the condition and third parameter is used to increase or decrease the variable value.

Syntax:-


for (start_expression; condition_expression; increment_or_decrement_expression)

Example1:- Suppose, You have a variable $x and that has value 1 and you increase the $x value until $x value will be 4.


<?php
for ($x = 1; $x < 5; $x++) {
print $x ."<br/>";
}
?>
1
2
3
4

Try it Yourself

Example2:- Suppose, You have a variable $x and that has a value 5 and you decrease the $x value until $x value will be 2


<?php
for ($x = 5; $x>1; $x--) {
print $x ."<br/>";
}
?>
5
4
3
2

Try it Yourself

Php switch statement

Php switch statements to replace complicated if-elseif statements. Switch statements compare an expression against all of the possible entries inside their body. If they don’t find an exact match, the program will run the “default” clause and ignore the rest of the statement. In PHP, you may use a “break” statement to terminate the code’s execution and pass the control to the succeeding scripts.

Syntax:-


<?php
switch (expression) {
case expression:
statement1
case expression:
statement2
...
default:
statementn
}
?>

Example:-


<?php
$game = "Cricket";
switch ($game) {
  case "Cricket":
    echo "Sachin belongs to cricket!";
    break;
  case "Hockey":
    echo "Dhayan Chand belongs to Hockey";
    break;
  case "Tennis":
    echo "Mahesh Bhupathi belongs to Tennis!";
    break;
  default:
    echo "Players neither belongs to Cricket, Hockey, nor Tennis!";
}
?>
Output:- Sachin belongs to cricket!

Try it Yourself

Php if else condition

In PHP, if-else is used for conditional statements. there are 3 types to use if-else condition.

1) if condition:- “if” condition will be executed when “if” statement is true.

Syntax:-


<?php
if(conditional_expression)
{

}
?>

Example:- Suppose, You have $x variable and that has value 100 and now you create the condition.


<?php
$x=100;
if($x>90)
{

 echo 'condition is passed';

}
?>
condition is passed

Try it Yourself

2) if else condition:- “if” condition will be executed when “if” statement is true otherwise false condition will be executed.

Syntax:-


<?php
if(conditional_expression)
{

}else{
}
?>

Example:- Suppose, You have $x variable and that has value 80 and now you create the condition.


<?php
$x=80;
if($x>90)
{

 echo 'condition is passed';

}else{

 echo 'condition is failed';

}
?>
condition is failed

Try it Yourself

3) if elseif condition:- “if” condition will be executed when “if” statement is true otherwise check else if condition.

Syntax:-


<?php
if(conditional_expression1)
{

}elseif(conditional_expression2)
{

}else{

}
?>

Example:- Suppose, You have $x variable and that has value 80 and now you create the condition.


<?php
$x=80;
if($x>90)
{

 echo 'x value is greater than 90';

}elseif($x>70 && $x<90){

 echo 'x value is between 70 to 90';

}else{
echo 'condition does not match';
}
?>
x value is between 70 to 90

Try it Yourself

PHP Operator

The PHP language supports basically two types of operators.
1) Unary operator
2) Binary operator

1) Unary Operator:- The Unary Operator works only on single operands.

Increment and Decrement Operator

a) Increment Operator:- There are two types of Operator.

(i) Post-Increment:- It represents ++ sign after variable like $varable++. This is called Post-increment operator. It returns the current value of the variable and increases it by 1.


<?php
$x=100;
echo $x++;
?>
Output:- 100

Try it Yourself

(ii) Pre-Increment:- It represents ++ sign before the variable like ++$varable This is called Pre-increment operator. It increases the value of the variable by 1 and returns the resulting value..


<?php
$x=100;
echo ++$x;
?>
Output:- 101

Try it Yourself

b) Decrement Operator:- There are two types of operator.

Post-Decrement:- It represents — sign after variable like $varable–. This is called Post-Decrement operator. It returns the current value of the variable and decrease it by 1.


<?php
$x=100;
echo $x--;
?>
Output:- 100

Try it Yourself

Pre-Decrement:- It represents — sign before the variable like –$varable This is called Pre-Decrement operator. It decrease the value of the variable by 1 and returns the resulting value.


<?php
$x=100;
echo --$x;
?>
Output:- 99

Try it Yourself

Cast Operator

PHP Language has six cast operators that you can use to force type conversions. You should place the operator on the left-side of the operand.

(array) – This operator converts values into an array.


<?php
$x=100;
$y= (array)$x;
print_r($y);
?>
Output:- Array ( [0] => 100 )

Try it Yourself

(int) or (integer) – This operator convert values into integers.


<?php
$x="100";
$y= (int)$x;
echo $y;
?>
Output:- 100

Try it Yourself

(string) – This operator converts values into a string.


<?php
$x=100;
$y= (string)$x;
echo $y;
?>
Output:- “100”

Try it Yourself

(object) – This operator convert values into the object.


<?php
$x=100;
$y= (object)$x;
print_r($y);
?>
Output:- stdClass Object ( [scalar] => 100 )

Try it Yourself

(real), (float) or (double) – This operator allows you to convert values from any data type into floating-point values.


<?php
$x="100";
$y= (double)$x;
echo gettype($y);
?>
Output:- double

Try it Yourself

(bool) or (boolean) – Use this operator to convert any value into its Boolean form.


<?php
$x="100";
$y= (bool)$x;
echo gettype($y);
?>
Output:- boolean

Try it Yourself

The Negation Operators

PHP language support 2 types of Negation Operators.

a) Logical Negation Operator:- It represents through ! operator. It will give you true if the operand’s value is false. If the value is true, on the other hand, this operator will give you false.


<?php
$x=100;
if(!$x){

echo 'x variable does not exist';

}else{

echo 'x variable exists';

}
?>
Output:- x variable exists

Try it Yourself

b) Bitwise Negation operator:- It represents through “~” operator. It replaces 0 with 1, and vice versa.

2) Binary Operator:- A binary operator requires two Operands.

The Numeric Operators

There are 5 numeric operator.

(i) Addition Operator:- It represents “+” sign between two operands and return the sum value.


<?php
$x=100;
$y=40;
$z=$x+$y;
echo $z;
?>
Output:- 140

Try it Yourself

(ii) Subtract Operator:- It represents “-“ sign between two operands and returns the subtraction value from left operands to right operands.


<?php
$x=100;
$y=40;
$z=$x-$y;
echo $z;
?>
Output:- 60

Try it Yourself

(iii) Multiplication Operator:- It represents “*” sign between two operands and returns the multiply value.


<?php
$x=100;
$y=40;
$z=$x*$y;
echo $z;
?>
Output:- 4000

Try it Yourself

(iv) Division Operator:- It represents the “/” sign between two operands and It divides the value of the left-hand operand by that of the right-hand operand and returns the quotient.


<?php
$x=100;
$y=40;
$z=$x/$y;
echo $z;
?>
Output:- 2.5

Try it Yourself

(v) Modulus Operator:- It represents the “%” sign between two operands and divides the value of the left-hand operand by that of the right-hand operand and returns the remainder.


<?php
$x=100;
$y=40;
$z=$x%$y;
echo $z;
?>
Output:- 20

Try it Yourself

Assignment Operator

An assignment operator allows you to assign values to your variables. Assignment operators are used with numeric values.

= operator:- It is used to assign the value.


x=2;

+= operator:- it is basically used to addition between two operands.


x+=y like x=x+y;

Try it Yourself

-= operator:- it is basically used to subtraction between two operands.


x-=y like x=x-y;

Try it Yourself

*= operator:- it is basically used to multiplication between two operands.


x*=y like x=x*y;

Try it Yourself

/= operator:- it is basically used to division between two operands.


x/=y like x=x/y;

Try it Yourself

%= operator:- it is basically used to modulas between two operands.


x%=y like x=x%y;

Try it Yourself

Comparison Operator

You can use these operators to compare the values of two operands.

“==” Operator – This operator checks whether the operands have equal values. It will give you true if the values are equal.

example,


$x == $y

Try it Yourself

“!=” Operator – if the value of the operand are not equal. For instance,


100 != 40

evaluates to true.
Try it Yourself

“>” Operator – this refers to greater than the operator. you can check whether the value of the left-hand operand is greater than that of the right-hand operand.
Try it Yourself

“<" Operator - this refers to less-than operator. you can check whether the value of the left-hand operand is less than that of the right-hand operand.
Try it Yourself

“<=" Operator - this refers to less than or equal operator. It will give you true if the value of the left-hand operand is less than or equal to the second operand.

Try it Yourself

“>=” Operator – this refers to greater than or equal operator. It will give you true if the value of the left-hand operand is greater than or equal to the second operand.

example, $x >= $y
Try it Yourself

Logical Operator

PHP represents some Logical operator.

(i) Logical AND:- this represents through “&&”. It will give you true if the both operands are true.


$x && $y

Try it Yourself

(ii) Logical OR:- this represents through “||”. It will give you true if the one operands is true.


$x || $y 

Try it Yourself

(iii) Logical XOR:- this represents through “xor”. It will give you true if only one of the operands is true. Thus, you will get false if both of the operands are true or false.
Try it Yourself

Concatenation Operator

this operator is used to concate the two or more strings. It works only for strings value.
It converts non-string operands to string operands.


<?php
$emp_age = 23;
print "Employee age is " . $emp_age;
?>
Employee age is 23

Try it Yourself

PHP Conditional Assignment Operator

Ternary Operator(?:)- this operator is used to check conditions.

Syntax:-


conditional_statement ? first_expression : second_expression

The “?” operator evaluates the result of “conditional_statement” If the result is true, the
operator will return the value of “first_expression”. If the result is false, the operator will
give you the value of “second_expression”.

Example:-


<?php
$x=10;
echo ($x==10) ? 'even number': 'odd number';
?>
Output:- even number

Try it Yourself

coalescing operator (??)- PHP7 introduce coalescing operator. The Null coalescing operator returns its first operand if it exists and is not NULL otherwise, it returns its second operand.


<?php
$employee='John';
$employee_name = $employee ?? 'employee not exists';
/** This is equivalent to: **/
$employee_name = isset($employee) ? $employee : 'employee not exists';
?>
Output:- John

Try it Yourself

Php Constants

PHP Constant is a variable and you can use it anywhere in the code.
A constant variable doesn’t need a dollar($) sign before its name.
You can not alter a PHP constant once you have assigned its value.
You can create Php constant variable through the define() keyword.

How to create constant variable?

You can create a constant variable through the define() keyword. It has three parameters.

Syntax:-


<?php
define(NAME_OF_CONSTANT,VALUE,CASE-INSENSITIVE);
?>

NAME_OF_CONSTANT:- It represents the name of the constant variable. NAME_OF_CONSTANT that consists of letters and numbers. Constant variable name should be in upparcase format. It is mandatory.

VALUE:- It represents constant variable value. It is mandatory.

CASE-INSENSITIVE:- It represents case-sensitive false or true. By-default repesents false. It is optional.

Example:- Suppose, You create a constant variable REMOVELOAD_ACADEMY and put the value Removeload Academy is a free e-learning tutorial Portal after that call it through the constant variable name.


<?php
define('REMOVELOAD_ACADEMY','Removeload Academy is a free e-learning tutorial Portal');
echo REMOVELOAD_ACADEMY;
?>
Output:- Removeload Academy is a free e-learning tutorial Portal

Try it Yourself

Example:- Now, you define the CASE-INSENSITIVE true.


<?php
define('REMOVELOAD_ACADEMY','Removeload Academy is a free e-learning tutorial Portal',true);
echo removeload_academy;
?>
Output:- Removeload Academy is a free e-learning tutorial Portal

Try it Yourself

PHP Constant Array

In PHP7, you can create constant variable value into an array format.

Example:-


<?php
define('SOFTWARE_COMPANIES',array('TCS','HCL','Infosys','Oracle'));
echo SOFTWARE_COMPANIES[0]; //TCS
echo SOFTWARE_COMPANIES[1]; //HCL
echo SOFTWARE_COMPANIES[2]; //Infosys
echo SOFTWARE_COMPANIES[3]; //Oracle
?>

Try it Yourself

Php Datatype

Php support 8 types of datatype. PHP variables behave according to the type of data they hold.

Integer
Float
String
Array
Object
Boolean
Null
Resources

Php Integer

Php Integer is a whole number means it is not decimal number.
Range of Integer variable value are from -2,147,483,648 to 2,147,483,647
Integer variable value can be positive or negative.

Example:- Suppose you have $num variable which has value 2500 and you can use var_dump() method to get datatype and variable value.


<?php
$num=2500;
var_dump($num);
?>
Output:- int(2500)

Try it Yourself

Php Float

Php floating-point number is also called real number. A floating number has decimal point and it has positive and negative sign before number.

Example:- Suppose you have $num variable which has value 2.5 and you can use var_dump() method to get datatype and variable value.


<?php
$num=2.5;
var_dump($num);
?>
Output:- float(2.5)

Try it Yourself

Php String

Php strings are sequences of characters (i.e. letters and numbers)
While adding a string value to your PHP code through single quotes or double quotes.

Single Quotes – This is the simplest option that you can use when creating a string.
Write your string between a pair of quotes.

Example:- Suppose you have $employee_name variable which has value John Taylor.


<?php
$employee_name='John Taylor';
echo $employee_name;
?>
Output:- John Taylor

Try it Yourself

Double Quotes – double quotes strings can hold the variable value.
Example:- Suppose you have $employee_name variable which has value John Taylor.


<?php
$employee_name='John Taylor';
$employee_greetings ="Hello $employee_name";
echo $employee_greetings;
?>
Output:- Hello John Taylor

Try it Yourself

Php Array

PHP array is a group of key and value pairs. array index can be integer or string. Phy array has multiple value into single variable.

Declare Php Array through array()
Syntax:-


<?php
$var=array();
?>

Example:- Suppose, You create a employee_name array which has multiple values and get the value.


<?php
$employee_name=array('John','Rom','Mathew');
echo $employee_name[0];  // John
echo $employee_name[1];  // Rom
echo $employee_name[2];  // Mathew
?>

Try it Yourself

Declare key and value into the array()
Suppose, You create a employee array which has keys and values and get the values based on the array key.


<?php
$employee=array('name'=>'John','age'=>5, 'designation'=>'Software Engineer');
// get the array element value
echo $employee['name'];
echo $employee['age'];
echo $employee['designation'];
?>

Try it Yourself

Php Object

Php Object is an instance of a class.
An entity that has state and behavior is known as an object like a car, cycle, table, chair, etc.

Example:- Suppose you create Employee class which has property name $empname and function display_empname() and after that create object through new keyword.


<?php
class Employee {
    public $empname;
    function display_empname($empname) {
        return $empname;
    }
 
}
$emp_obj = new Employee;
echo $emp_obj -> display_empname('John');
?>
Output:- John

Try it Yourself

Php Boolean

Php boolean is used in conditional codes like (if, loops, etc.) statements. You should know that data types are often converted to Boolean during runtime.

Php boolean has two state
1) true or 1
2) false or 0

Example:-


<?php
$a=true;
or
$b= false;
?>

Php NULL

Php NULL data type can only have a NULL value. You can use NULL datatype as a empty variables.

The isset() operator gives false output for Null values if the variable being checked exists while you use other data type then isset() will give you true if the variable exists .

Example:-


<?php
$x=NULL;
if(isset($x)){
echo 'success';

}else{
 echo 'fail';
}

?>
Output:- fail

Try it Yourself

Php Resource

PHP resource a special type of data. It represents an extension resource of PHP such as an open file.
You can not handle a resource variable directly.
You can simply send it to different functions that can interact with the involved resource.

Php Super Global Variable

Variables that you can access from any part of your code is called global variable. In Php, you can not create global variable but PHP use some variable that act like as super global variable.

There are some superglobal variables

$_ENV[]:-This is an array that contains environment variables.


<?php
print_r($_ENV);
?>

$_GET[]:- This is an array and holds all of the GET variables gathered from the user’s web browser.


<?php
print_r($_GET);
?>

$_POST[] – This is an array and holds all of the POST variables gathered from the user’s web browser.


<?php
print_r($_POST);
?>

$_SERVER[] – This kind of array holds the values of web-server variables.


<?php
print_r($_SERVER)
?>

It will show all web server variables value like HTTP_HOST, HTTP_CONNECTION, etc.

Php empty() method

PHP empty() method is used to check the variable has value or not. It gives output in a boolean value. if the variable empty then the output will be true or 1 and if the variable is not empty then the output will be false or 0.

Syntax:- to check the variable is empty


<?php
empty($variable_name)
?>

Example:- Suppose, You have employee_name variable which has empty value and now you want to check employee_name variable is empty or not.


<?php
$employee_name="";
if(empty($employee_name))
{
echo 'employee is empty';
}

?>
Output:- employee is empty

Try it Yourself

Php unset() method

Php unset() method is used to delete the variable. when you unset the variable then variable is deleted and it release the occupied memory by the variable.
unset() method is used to delete the array element and object property also.

Syntax:-


<?php
unset($variable_name);
?>

Example:- Suppose, You have an employee_name variable and you unset this variable and after that print, this variable then shows the Undefined variable: employee_name.


<?php
$employee_name="John";
unset($employee_name);
echo $employee_name;
?>
Notice: Undefined variable: employee_name

Try it Yourself

Delete the Array element through unset() method

If you want to delete the array then use unset() method.

Syntax:-


<?php
unset($array_element);
?>

Example:- Suppose, You have an emp_arr array and you want to unset this array element which is on zero position then use unset() method.


<?php
$emp_arr=array("John","Tom","Mathew");
unset($emp_arr[0]);
print_r($emp_arr);
?>
Output:- Array ( [1] => Tom [2] => Mathew )

Try it Yourself

Php isset() method

PHP isset() method is used to check the variable or array or object’s property is exists or not. It gives output in a boolean value. if the variable or array element or object’s property exists then the output will be true or 1 and if the variable or array or object’s property does not exist then the output will be false or 0.

Syntax:- to check the variable


<?php
isset($variable_name)
?>

Example:- Suppose, You have employee_name variable which has value John and now you want to check employee_name variable is exists or not.


<?php
$employee_name="John";
if(isset($employee_name))
{
echo $employee_name.' is exists';
}

?>
Output:- John is exists

Try it Yourself

Example2:- Suppose, You check employee_age exists or not


<?php
if(isset($employee_age))
{
echo $employee_age.' is exists';

}else{

echo 'employee age does not exist';

}

?>
Output:- employee age does not exist

Try it Yourself

Php Variable

Php variable is different from other programming languages like Java, .Net, c, c++, etc because PHP variable is weakly typed and you can change the datatype of the variable whenever you want. You can use PHP variable without prior declaration.
Php variable is introduced through the dollar($) sign.


<?php
$name='John';
?>

Display the varible value through echo or print

echo and print is used to display the value.

Example:-


<?php
$name='John';
echo $name;
?>

Try it Yourself

Output:- John

Example:-


<?php
$name='John';
print $name;
?>
Output:- John

Try it Yourself

Declare PHP variable

You can declare variables through the string, underscore, and numbers but the first character should not be a number.

Example:- Suppose, You declare variable through $name variable.


<?php
$name='John';
echo $name;
?>
Output:-John

Example:- Suppose, You declare variable which is start through underscore (_) through $_name variable.


<?php
$_name='John';
echo $_name;
?>
Output:-John

Example:- Suppose, You declare variable $1_name then it will show error when you echo this variable


<?php
$1_name='John'; 
echo $1_name;
?>
Ouput:-syntax error, unexpected ‘1’ (T_LNUMBER), expecting variable (T_VARIABLE)

Weakly Datatype

Php variable datatype is weakly datatype.

Example:- Suppose, you declare string value into name variable after that you defined numeric value into name variable then it will show last update value.


<?php
$name="John";
$name= 25;
echo $name
?>
Output:-25

Try it Yourself

Indirect Reference

PHP allows you to access a variable using indirect reference. There are no limits regarding the number of indirect references that you can use.


<?php
$car = 'TataNexon'; 
$TataNexon = "This is developed by Tata Motors";
echo $$car;
?>
Output:- This is developed by Tata Motors

Try it Yourself

In the above example firstly execute $car variable and get the value TataNexon after that $TataNexon variable will execute and get the value This is developed by Tata Motors.

Php Comments

Developers use comments to describe the details of the code. In PHP there is three-way to describe the comments.

Shell Method

this method is used to single-line comment and it is used through # to comment the details.


<?php
# describe about code details
?>

Example:- Suppose, You created user_greetings function in the user file.


<?php

# user file

function user_greetings($name){

	return 'Hello '.$name;
}
echo user_greetings('John');
?>
Output:- Hello John

Try it Yourself

Single-line Comment

It is basically used for single-line comment and it works the same as the shell method. this method is copied from the c language.

Syntax:-


<?php
 // describe about code details
?>

Example:- Suppose, You created user_full_name function in the user file.


<?php
// get user full name function

function user_full_name($first_name,$last_name){

	return $first_name.' '.$last_name;
}

echo user_full_name('John','Taylor');
?>
Output:- John Taylor

Try it Yourself

Multi-line Comment

this method is used to comments for multiple lines. this method is copied from the c++ language.

Syntax:-


<?php
 /* 
describe 
about 
code details
*/
?>

Example:- Suppose, You created sum of nunbers in the user file and you defined multi-line comments for number1 and number2 .


<?php
/*
$number1=10
$number2=20;
*/
$number3=30;
$number4=40;

$sum_of_numbers=$number3+$number4;

echo $sum_of_numbers;
?>
Output:- 70

Try it Yourself

Nodejs Api request for cucumber test cases

To test the Nodejs API so please create the API in Nodejs.

Suppose you created a customer register API.


http://127.0.0.1:3333/api/register

Now, pass the requested data


   {  
         "first_name":"John",
	 "last_name":"Taylor",
	 "email":"john@gmail.com",
	 "password":"john123",
	 "cpass":"john123"
   }

Where first_name, last_name, email, password and cpass are request parameters.

Now, get the response


{  
    "status": 200,
    "message": "Customer Registered successfully."
}

To write the Cucumber test cases for Nodejs API in through the below steps

1) Firstly create a features folder in the root folder of your Nodejs project.

2) Now create the file name create_customer_via_jsonfile.feature extension and write the below code in this


# Create Customer API Testing Exercise via json file
Feature: Create new customer signup through json file
 Call API to create new customer through json file

  Scenario: Create new customer through json file
  
  Given create new customer through json file and data are
   """
   {  
         "first_name":"John",
	 "last_name":"Taylor",
	 "email":"john@gmail.com",
	 "password":"john123",
	 "cpass":"john123"
   }
  """

  When I send URL through POST method for JSON file http://127.0.0.1:3333/api/register

  Then response data is 
  """
  {  
    "status": 200,
    "message": "Customer Registered successfully."
   }
  """

  

in the create_customer_via_jsonfile.feature file, you have to create Feature: feature_name after that create the Scenario: scenario_name
after that, you have to create 3 steps
Given:- It is used for request data
When:- it is used for the condition
Then:- It is used for response data

3) Now create the create_customer_via_jsonfile_step folder and create create_customer_via_jsonfile_step.jsfile into this and put the below code.


// features/support/steps.js
const { Given, When, Then } = require("cucumber");
const assert = require("assert")
const got = require('got');

var output;
var jsonfile_body_request;


Given(/^create new customer through json file and data are$/, async function(request_data){
  jsonfile_body_request=request_data;
});

When('I send url through POST method for json file {}', async function(url) {

  const {body} = await got.post(url, {
		json: JSON.parse(jsonfile_body_request),
		responseType: 'json'
	});

  output={  
  "status": (body.status),
  "message": body.message
  }


});

Then(/^response data is$/, async function (expected_output) {
  var main_expected_output= JSON.parse(expected_output);
  assert.equal(JSON.stringify(output), JSON.stringify(main_expected_output));
});


4) Now, run the test cases


./node_modules/.bin/cucumber-js

Now, check the results and found the 1 scenarios, and 3 steps are passed.

Nodejs dynamic request for cucumber test cases

To write the dynamic request for cucumber test cases in Nodejs through the below steps

1) Firstly create a features folder in the root folder of your Nodejs project.

2) Now create the file name dynamic_req_calculation.feature extension and write the below code in this


# features/dynamic_req_calculation.feature

Feature: Dynamic request to add the variable
  
  I want to check the variable result

  Scenario Outline: dynamic request addition calculation
  Given a variable set to 
  When I increment the variable by 
  Then the variable should contain 

    Examples:
      | variable | increment_variable | result |
      | 10       |    5               |  15    |
      | 25       |    30              |  55    |
      | 100      |    10              |  110   |

in the dynamic_req_calculation.feature file, you have to create Feature: feature_name after that create the Scenario: scenario_name
after that, you have to create 3 steps
Given:- It is used for request data
When:- it is used for the condition
Then:- It is used for response data

Now define the dynamic request value in the Examples: like variable, increment_variable and the result will show the addition of these variables (variable+increment_variable).

3) Now create the calculation_support folder and create two files into this.

1) firstly create a world.js file which has below code


// features/support/world.js
const { setWorldConstructor } = require("cucumber");

class CustomWorld {
  constructor() {
    this.variable = 0;
  }

  setTo(number) {
    this.variable = number;
  }

  incrementBy(number) {
    this.variable += number;
  }

  multiplyBy(number) {
    this.variable *= number;
  }
}

setWorldConstructor(CustomWorld);

2) Now create the step.js file and write the below code in this.


// features/support/steps.js
const { Given, When, Then } = require("cucumber");
const assert = require("assert").strict

Given("a variable set to {int}", function(number) {
  this.setTo(number);
});

When("I increment the variable by {int}", function(number) {
  this.incrementBy(number);
});

Then("the variable should contain {int}", function(number) {
  assert.equal(this.variable, number);
});

3) Now, run the test cases


./node_modules/.bin/cucumber-js

Now, check the results and found the 3 scenarios and 9 steps are passed.

Nodejs simple request for cucumber test cases

To write the simple request for cucumber test cases in Nodejs through the below steps

1) Firstly create a features folder in the root folder of the Nodejs project.

2) Now create the file name simple_calculation.feature extension and write the below code in this


# features/simple_calculation.feature

Feature: Simple math calculation
  
  I want to check the increment variable result

  Scenario: easy math calculations
    Given a variable set to 4
    When I increment the variable by 5
    Then the variable should contain 9

in the simple_calculation.feature file create Feature: feature_name after that create the Scenario: scenario_name
after that, you have to create 3 steps
Given:- It is used for request data
When:- it is used for the condition
Then:- It is used for response data

3) Now, run the test cases


./node_modules/.bin/cucumber-js

Now, check the results 1 scenario and 3 steps are passed.

Install cucumber tool in Nodejs

Firstly open the terminal after that move to the root folder of your Nodejs Project then write the below command.


npm install --save-dev cucumber

After installing the cucumber then you can check the package name in the package.json file.


  "devDependencies": {
    "cucumber": "^7.0.0-rc.0"
  }

After installing the package, firstly you have to create a features folder at the root of your project.
after creating the folder you can create a file with .feature extension.
like mytest.feature

Run the cucumber test cases

Now write the test cases and run the test cases through the below command


./node_modules/.bin/cucumber-js

What is Cucumber?

Cucumber is a software testing tool and nowadays it is famous in the market because it is based on BDD (Behavior Driven Development). Cucumber testing software runs automated acceptance tests written in a behavior-driven development (BDD) style.
It has a stable release on 13 July 2018.
It is basically written in Ruby programming language. Cucumber uses Gherkin language to define the test cases. It is used for cross platform and you can use this tool in many programming languages like Java, .Net, Nodejs, PHP, etc.

What is Behavior Driven Development?

It encourages collaboration between everyone involved in developing software like developers, testers, and business representatives such as product owners or business analysts.

What is the goal of BDD?

the main goal of BDD is to improve the collaboration between all stakeholders involved in developing software like developers, testers, and business representatives such as product owners or business analysts and form a shared understanding among them.

Cucumber has two basic components known as features and scenarios.

What are features?

Features are a file with a .feature extension that has multiple scenarios.

What are Scenarios?

Scenarios are plain English statements that completely state what the feature is and what it is supposed to perform. They are actions taken by the user and the outcome of these actions in the form of a response from the website.

Features file has 3 sections.
Given – These steps are used to set up the initial state before you do your test.
When – These steps are the actual test that is to be executed.
Then – These steps are used to assert the outcome of the test.

Example:- to create the file name simple_calculation.feature extension and write the below code in this


# features/simple_calculation.feature

Feature: Simple math calculation
  
  I want to check the increment variable result

  Scenario: easy math calculations
    Given a variable set to 4
    When I increment the variable by 5
    Then the variable should contain 9

Javascript Hoisting

Javascript Hoisting is a mechanism that moves all variable and function declarations to the top of their scope before code execution. However, variable assignments still happen where they originally were.
Note:- variable declaration is hoisted while the assignment remains in the same place.


console.log(emp_name);
var emp_name = "John";
Output:-
undefined

Note:- undefined means value is not defined in the variable.

Hoisting Process of above code

Now, the javascript hoisting mechanism run the above code into 3 steps
step1:- firstly declare emp_name variable


var emp_name

step2:- Now run the console.log


console.log(emp_name);

step3:- Now defined the emp_name value


emp_name = "John";

Complete hoisting process of the above code


var emp_name
console.log(emp_name);
emp_name = "John";
Output:-
undefined

call the variable after defined the value


var emp_name; // → Hoisted variable declaration
console.log(emp_name); // → undefined
emp_name = "John"; // → variable assignment remains in the same place
console.log(emp_name); // → John
Output:-
undefined
John

Hoisting Rule does not work when used ‘use strict’ before the code


'use strict';
console.log(emp_name); 
emp_name = 'John'; 
Output:-
Uncaught ReferenceError: emp_name is not defined

Javascript Hoisting Rule for function

function declarations are hoisted to the top of their scope.


display_name();
function display_name() {
  var emp_name='John'
    console.log('Hello '+emp_name);
}
Output:-
Hello John

Hosting process of the function of the above code


function display_name() {
  var emp_name='John'
    console.log('Hello '+emp_name);
}
display_name();

Javascript Hoisting Rule does not work for function expression


display_name();
var display_name= function() {
  var emp_name='John'
  console.log(emp_name);
}
Output:-
Uncaught TypeError: display_name is not a function

Javascript Closure function

Closure function is a part of advanced javascript, It is basically used to access outer function parameters and variables in the inner function so this inner function is called closure function.
the inner function returns into the outer function.

Suppose, you have a outer function start() and declared employeeName variable in this and called this variable into displayEmployeeName() inner function.


function start() {
  var employeeName = 'John'; // employeeName is a local variable created by start function
  function displayEmployeeName() { // displayEmployeeName() is the inner function, a closure
    console.log("Hello "+employeeName); // employeeName variable declared in the parent function
  }
  displayEmployeeName();
}
start();
Output:-
Hello John

Suppose, you have defined x variable value into the outer scope and captured the x variable value into inner scope function getNum()


var x = 5; // declaration in outer scope
function getNum() {
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 5 to console
Output:-
5

Suppose, You change the outer scope variable x value into the inner function scope then the value will be change.


var x = 5; // declaration in outer scope
function getNum() {
x=2;
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 2 to console
Output:-
2

Javascript Object Deep copy

Javascript Object deep copying means that the value of the new variable is disconnected from the original variable.
You can create the deep copying through JSON.parse method with JSON.stringify

Syntax:-


let new_object_name = JSON.parse(JSON.stringify(object_name));

Example:- Suppose you have employee object and copy object through JSON.parse() method with JSON.stringify into new_employee object then you change the firstName, city and state in new_employee object then it will not connected to old employee object.


let employee = {
    firstName: 'John',
    lastName: 'Taylor',
    address: {
        city: 'Mumbai',
        state: 'Maharashtra',
        country: 'India'
    }
};


let new_employee = JSON.parse(JSON.stringify(employee));
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // disconnected
new_employee.address.state = 'Delhi'; // disconnected
console.log(new_employee);
console.log(employee);
Output:-
newEmployee:- {
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}

oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “Mumbai”, state: “Maharashtra”, country: “India”}

}

Javascript Object shallow copy

A Javascript shallow copy means that the primitive datatype value of the new variable is disconnected from the original variable and the compositive datatype value of the new variable is connected from the original variable.

You can create shallow copy through the below methods.

1) Object.assign(target_object,source_object);
2) through spread operator

1) Copy through Object.assign() method

Syntax:-


var new_object=Object.assign({},object)

Example:-
Suppose, You have an employee object and copy object through Object.assign() into new object new_employee


let employee = {
    firstName: 'John',
    lastName: 'Taylor',
    address: {
        city: 'Mumbai',
        state: 'maharashtra',
        country: 'India'
    }
};


let new_employee = Object.assign({}, employee);
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // connected
new_employee.address.state = 'Delhi'; // connected
console.log("newEmployee:-",new_employee);
console.log("oldEmployee:-"employee);
Output:-
newEmployee:- {
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}

oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}

}

2) Copy through spread operator

Syntax:-


var new_object={...Object};

Example:-
Suppose, You have an employee object and copy object through spread operator (…) into new object new_employee


let employee = {
    firstName: 'John',
    lastName: 'Taylor',
    address: {
        city: 'Mumbai',
        state: 'maharashtra',
        country: 'India'
    }
};


let new_employee = {...employee};
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // connected
new_employee.address.state = 'Delhi'; // connected
console.log("newEmployee:-",new_employee);
console.log("oldEmployee:-"employee);
Output:-
newEmployee:- {
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}

oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}

}

JavaScript Arrow function

Javascript Arrow function came into ES6 (ECMAScript 6). Arrow functions don’t bind this keyword to the object.
Arrow functions are best for callbacks or methods like map, reduce, or forEach, etc.

in Arrow function do not write function keyword.

Arrow function without parameter

Syntax:-


arrow_function_name:()=>{
return 'Hello';
}

Example:- Suppose, you have a greetings object and that has the say_hello method without parameter..


let greetings={
say_hello:()=>{
return 'Hello';
}
}
console.log(greetings.say_hello());
Output:-
Hello

Arrow function with parameters

Syntax:-


arrow_function_name:(param1, param2)=>{
return param1+param2;
}

Example:- Suppose, you have a greetings object and that has the say_hello method with parameter friend_name.


let greetings={
say_hello:(friend_name)=>{
return 'Hello '+friend_name;
}
}
console.log(greetings.say_hello('Rom'));
Output:-
Hello Rom

Arrow function do not bind this keyword to the object

Suppose, you have employee object and you want to call first_name and last_name through this keyword in full_name method then output will show undefined.


let employee = {
  first_name: 'John',
  last_name:'Taylor',
  full_name: () => { 
    console.log(this.first_name+' '+this.last_name)  
  }
}
employee.full_name();
Output:-
undefined undefined

Simple function bind this keyword to the object

Suppose, you have employee object and you want to call first_name and last_name through this keyword in full_name method then output will show first_name and last_name values.


let employee = {
  first_name: 'John',
  last_name:'Taylor',
  full_name: function () { 
    console.log(this.first_name+' '+this.last_name)  
  }
}
employee.full_name();
Output:-
John Taylor

Javascript Non enumerable property

Javascript Non-enumerable property is used when you do not want to reassign the value of the key of the object. The non-enumerable property of the object does not show when you iterate through the object using for…in loop or using Object.keys() to get an array of property names.


var employee = {
  name: 'John'
};
employee.salary = '$2000';
employee['country'] = 'USA';

console.log(Object.keys(employee)); // ['name', 'salary', 'country']

As we know that employee object properties name, salary, country are enumerable hence it’s shown up when we called Object.keys(employee).

How to create non-enumerable property of the object?

To create a non-enumerable property we have to use Object.defineProperty() and defined enumerable:false. This is a special method for creating a non-enumerable property in JavaScript.


// Create non-enumerable property
Object.defineProperty(employee, 'phoneNo',{
	value : 3333333333,
	enumerable: false
})

console.log(Object.keys(employee));
Output:- [‘name’, ‘salary’, ‘country’]

Note:- phoneNo is not showing in the output because it is a non-enumerable property.

Now let’s try to change value of phoneNo


employee.phoneNo = 4444444444; 
console.log(employee.phoneNo);
Output:- 3333333333

Note:- phoneNo value will not change and show old value.

How to empty an array list in JavaScript?

There are three method to empty the array list
Method1:- arrayList defined empty array.
Syntax:-


var arrayList=[];

Example:-


var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list;  // Referenced arrayList by another variable
array_list = []; // Empty the array  
console.log(array_list); //Output []
console.log(new_array_list); // Output ['a', 'b', 'c', 'd', 'e', 'f']

Note:- if you changed original array variable then reference array will remain unchanged.

Method2:-
Syntax:-


var arrayList.length=0;

Example:-


var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list;  // Referenced array_list by another variable
array_list.length = 0; // Empty the array by setting length to 0
console.log(array_list); // Output []
console.log(new_array_list); // Output []

Note:- This way of empty the array also update all the reference variable which pointing to the original array.

Method3:-
Syntax:-


arrayList.splice(0, arrayList.length);

Example:-


var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list;  // Referenced array_list by another variable
array_list.splice(0, array_list.length); // Empty the array by setting length to 0
console.log(array_list); // Output []
console.log(new_array_list); // Output []

How to reverse string in Javascript?

If you want to reverse string in javascript then use the reverse() method


var string = "Welcome to Javascript!";
console.log(string.split("").reverse().join(""));
Output:-
!tpircsavaJ ot emocleW

Reverse string without pre defined function


var string = "Welcome to Javascript!";
var arr= string.split("");
var i=0;
var new_arr=[];
for(i=arr.length-1; i>=0; i--){
  new_arr.push(arr[i]);

}
console.log(new_arr.join(""));
Output:-
!tpircsavaJ ot emocleW

Reverse only string words


var string = "Welcome to Javascript!";
let data= string.split(" ");
let revdata=[];
for(let i=0; i<(data.length); i++)
{
 revdata.push(data[i].split("").reverse().join(""));

}	
console.log(revdata.join(" "));
Output:-
emocleW ot !tpircsavaJ

Nodejs json web token

JWT is used to secure web token. JWT stands for JSON Web token.
JWT is used to encrypt the token so that no one hacks the token.

How to install JSON Web Token in Nodejs?


npm i jsonwebtoken

How to create JSON Web Token token in Nodejs?

Suppose, you create createjwt.js file
include jsonwebtoken through require method


var jwt = require('jsonwebtoken');
module.exports.create_jwt_token= async ()=>{
let role=1;
let email='john@abc.com'
let token = jwt.sign({role:role,email:email}, 'sh233444hh'); // save token into database
console.log("token:-",token);
}

Now, create the index.js file and include the createjwt.js file


var createjwt = require('./createjwt');
createjwt.create_jwt_token();
Output:-
token:- eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoxLCJlbWFpbCI6ImpvaG5AYWJjLmNvbSIsImlhdCI6MTYxMDE3MTk2N30.IGVdnytBjesv4PZld7TZuwqzfGoxL9DOYKK72QfoD0U

How to verify JWT token in Nodejs?

Suppose, you create verifyjwt.js file
include jsonwebtoken through require method


module.exports.verify_jwt_token= async (token)=>{
 
  jwt.verify(token, 'sh233444hh', async function(err, results) {
  if(err){

    console.log("error+++",err);

  }else{

    console.log(results);

  }

  })
  }

Now, create the index.js file and include the verifyjwt.js file


var verifyjwt = require('./verifyjwt');
var token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoxLCJlbWFpbCI6ImpvaG5AYWJjLmNvbSIsImlhdCI6MTYxMDE3MTk2N30.IGVdnytBjesv4PZld7TZuwqzfGoxL9DOYKK72QfoD0U";
var output=verifyjwt.verify_jwt_token(token);
console.log(output);
Output:-
{ role: 1, email: ‘john@abc.com’, iat: 1610173305 }

Nodejs Module

Nodejs Module is like a set of libraries. There are two types of Module
1) Package Module
2) Custom Module

1) Package Module:- This type of module is already created by the NPM community and you can use this.

Step1:- Firstly installed the package
Example:- You want to install http module then write below command


npm install http --save

Step2:- Now, create the index.js file and include the module through require method.


var http = require('http');
const httpServer = http.createServer(app);
httpServer.listen(4444,() => {
 console.log('HTTP Server running on port 4444');
});

2) Custom Module:- You can create your own module.

Suppose, you create a register.js file and write the signup method


module.exports.signup= async ()=>{

// logic implement in this
console.log("signup module is called");

}

Now, create the index.js file and include the register.js file through require method and call the signup method.


var register = require('register');
var data=register.signup();
console.log(data);
Output:-
signup module is called

How to call one file method into another file?

If you want to call one file method into another file then you must define the method through module.exports

Example:- Suppose, You create a file user_info.js and define the method user_details()


module.exports.user_details = async () => {

  var udetails={

    name:"John",
    age:35

  }
  console.log(udetails);
}

Now, create the index.js file and call the user_details method.


var user_info= require('./user_info');
user_info.user_details()
Output:-
{ name: ‘John’, age: 35 }

If you do not define the module.exports

You create a file user_info.js and define the method user_details()


user_details = async () => {

  var udetails={

    name:"John",
    age:35

  }
  console.log(udetails);
}

Now, create the index.js file and call the user_details method.


var user_info= require('./user_info');
user_info.user_details()
Output:-
TypeError: user_info.user_details is not a function

Nodejs bcrypt

Nodejs bcrypt is used to store the password in an encrypted format with hash and salt.

How to install bcrypt package in Nodejs?

Firstly installed bcrypt package through below command.


npm install --save bcrypt

How to generate password in encrypted format through bcrypt?

Bcrypt is used to generated secure passwords.

Suppose, You create generate_hash_password.js file and write the below code.


const bcrypt = require('bcrypt');
var password="Hello123"
const saltRounds = 10;  //write number
var hash_password = bcrypt.hashSync(password, saltRounds); //Password must be save into database
console.log("Hash Password:-",hash_password);
Output:-
Hash Password:-$2b$10$jgXSMwBDsysCirC5xMGYwue0kv7Q00H9.pGBcag6Awrkeb1Pu2o6.

Note:- firstly include bcrypt package through require method after that write the hashSync method of bcrypt.

How to compare encrypted password?

Firstly create the compare_password.js file and write the below code.


const bcrypt = require('bcrypt');
const saltRounds = 10;
var password='Hello123';
var hash_password = '$2b$10$jgXSMwBDsysCirC5xMGYwue0kv7Q00H9.pGBcag6Awrkeb1Pu2o6.'; //which is coming from database 
let encrypt_pwd = hash_password;
let check_password = bcrypt.compareSync(password, encrypt_pwd);
console.log("Password is:-",check_password);

Note:- compareSync method has two parameters
1) raw password
2) encrypted password

Output:-
Password is:-true

Nodejs email

To send the email in Nodejs through nodemailer package.
Firstly installed nodemailer package.


npm install --save nodemailer

Now open the URL https://mailtrap.io/

create the signup

get the username and password

Now, create the email.js file and write the below code


var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
  host: 'smtp.mailtrap.io',
  port: 2525,
  auth: {
     user: 'put_your_username_here', //put_your_username_here
     pass: 'put_your_password_here' //put_your_password_here
  }
});

var mailOptions = {
  from: 'fromemail@abc.com',
  to: 'toemail@abc.com',
  subject: 'Test Email',
  html: '

HTML body text data

' }; transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } });
Output:-
Email sent: 250 2.0.0 Ok: queued

Check the send email content in mailtrap inbox

Nodejs Mysql insert query

to create the MySQL insert query in Nodejs, I have defined 2 steps

Insert Single Record into the table

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the insert.js file and include the connection.js file and write the insert query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('insert into users(name,age) values(?,?)',['John',35], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the insert.js file.


node insert.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 1,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

IN this file, I have created an insert query to save records in the users table.

Now, get the results from the table


select * from users
ID
Name
Age
1
John
35

Insert Multiple Records into the table

Step:2) Now, create the insert.js file and include the connection.js file and write the insert query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('insert into users(name,age) values ?',[[['Rom',31],['Mathew',32],['Sachin',38]]], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the insert.js file.


node insert.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 2,
serverStatus: 2,
warningCount: 0,
message: ‘&Records: 3 Duplicates: 0 Warnings: 0’,
protocol41: true,
changedRows: 0 }

Now, get the results from the table


select * from users
Output:-
ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Nodejs Mysql update query

to create the MySQL update query in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now you want to change user name from John to Sunny and age from 35 to 31 which has userid 1.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the update.js file and include the connection.js file and write the update query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('update users SET name=?,age=? where id=?',['Sunny',31,1], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the update.js file.


node update.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ‘(Rows matched: 1 Changed: 1 Warnings: 0’,
protocol41: true,
changedRows: 1 }

Now, get the records from the users table.


Select * from users
Output:-
ID
Name
Age
1
Sunny
31
2
Rom
31
3
Mathew
32
4
Sachin
38

Nodejs Mysql delete query

to create the MySQL delete query in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now you want to delete user which has user id is 1

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the delete.js file and include the connection.js file and write the delete query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('delete from users where id=?',[1], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the delete.js file.


node delete.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

Now, get the users records from the table.


Select * from users
Output:-
ID
Name
Age
2
Rom
31
3
Mathew
32
4
Sachin
38

Node Mysql select query

to create the MySQL select query in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 2, name: ‘Rom’, age: 31 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 4, name: ‘Sachin’, age: 38 } ]

Nodejs Mysql select query with where condition

to create the MySQL select query with where condition in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now, you want to get the user details which has age 35.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users where age=?',[35], function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 1, name: ‘John’, age: 35 } ]

Nodejs Mysql Order By

to create the MySQL select query with Order By clause in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now, You want to get the user details based on age in ascending order.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users Order By age', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 2, name: ‘Rom’, age: 31 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 4, name: ‘Sachin’, age: 38 } ]

Now, You want to get the user details based on age in descending order so change the query in Step2

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users Order By age DESC', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 4, name: ‘Sachin’, age: 38 },
RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 2, name: ‘Rom’, age: 31 } ]

Nodejs Mysql Limit

MySql Limit is used to get the number of records from the table as your requirements.
to create the MySQL select query with a Limit clause in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Suppose, You want to get the user details based on limit 1.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users limit 1', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 1, name: ‘John’, age: 35 } ]

Nodejs Mysql create table

to create the table in MySQL, I have defined 2 steps.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the createtable.js file and include the connection.js file and write the query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('CREATE TABLE IF not exists users1 (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,name VARCHAR(50) NOT NULL,age INT(2) NOT NULL', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the createtable.js file.


node createtable.js
Output:-
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: ”,
protocol41: true,
changedRows: 0 }

Nodejs MongoDB create collection

MongoDB’s collection is like a table in RDBMS. to create the collection through createCollection() method.

Firstly create the create_collection.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.createCollection("users", function(err, res) {
      if (err) throw err;
       console.log("Collection is created");
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the create_collection.js file.


node create_collection.js
Output:-
Collection is created

Note:- If you have not collection then you create a document then it will check collection is exists or not it does not exists then it will create the collection.

Nodejs MongoDB Drop Collection

MongoDB’s collection is like a table in RDMS. if you want to drop the collection then use dropCollection() method

Firstly create the drop_collection.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.dropCollection("users", function(err, res) {
      if (err) throw err;
       console.log("Collection is removed");
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the drop_collection.js file.


node drop_collection.js
Output:-
Collection is removed

Now, you can check collection is removed or not in MongoDB through command


> show collections

Nodejs MongoDB insert document

MongoDB’s document is like a table’s row in RDBMS. to insert document into the collection through insertOne() or insertMany() method.

Insert one document through insertOne() method

Firstly create the insert_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var user_obj={name:"John",age:35}
     dbo.collection("users").insertOne(user_obj, function(err, res) {
      if (err) throw err;
       console.log("1 document is added into collection");
       console.log(res.ops);
       console.log(res.insertedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the insert_document.js file.


node insert_document.js
Output:-
1 document is added into collection
[ { name: ‘John’, age: 35, _id: 5fdc9e76304b8b785feb4ebf } ]
1

Insert multiple documents through insertMany() method

Firstly create the insert_documents.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
    if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var user_obj=[{name:"Rom",age:31},{name:"Mathew",age:32},{name:"Sachin",age:38}];
     dbo.collection("users").insertMany(user_obj, function(err, res) {
      if (err) throw err;
       console.log("documents are added into collection");
       console.log(res.ops);
       console.log(res.insertedCount);

       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the insert_documents.js file.


node insert_documents.js
Output:-
documents are added into collection
[ { name: ‘Rom’, age: 31, _id: 5fdcdb87b6dad382104b0f86 },
{ name: ‘Mathew’, age: 32, _id: 5fdcdb87b6dad382104b0f87 },
{ name: ‘Sachin’, age: 38, _id: 5fdcdb87b6dad382104b0f88 } ]
3

Nodejs MongoDB update document

MongoDB’s document is like a table’s row in RDBMS. to update document into the collection through updateOne() or updateMany() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

Update one document through updateOne() method

Firstly create the update_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var new_values={$set:{age:40}};
     var where_condition={name:"John"}
     dbo.collection("users").updateOne(where_condition,new_values, function(err, res) {
      if (err) throw err;
       console.log("1 document updated successfully");
       //console.log(res);
       console.log(res.result);
       console.log(res.modifiedCount);

       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the update_document.js file.


node update_document.js
Output:-
1 document updated successfully
{ n: 1, nModified: 1, ok: 1 }
1

Update multiple documents through updateMany() method

Firstly create the update_documents.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
   if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var new_values={$set:{age:45}};
     var where_condition={name:/o/}
     dbo.collection("users").updateMany(where_condition,new_values, function(err, res) {
      if (err) throw err;
       console.log("documents updated successfully");
       //console.log(res);
       console.log(res.result);
       console.log(res.modifiedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the update_documents.js file.


node update_documents.js
Output:-
documents updated successfully
{ n: 2, nModified: 2, ok: 1 }
2

Nodejs MongoDB delete document

MongoDB’s document is like a table’s row in RDBMS. to delete document from the collection through deleteOne() or deleteMany() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

delete one document through deleteOne() method

Firstly create the delete_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var where_condition={name:'Mathew'}
     dbo.collection("users").deleteOne(where_condition, function(err, res) {
      if (err) throw err;
       console.log("1 document deleted successfully");
       console.log("result:",res.result);
       console.log("deleted_count:",res.deletedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the delete_document.js file.


node delete_document.js
Output:-
1 document deleted successfully
result: { n: 1, ok: 1 }
deleted_count: 1

delete multiple documents through deleteMany() method

Firstly create the delete_documents.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
   if (err) throw err;
     var dbo = connection_obj.db("users_management");
     var where_condition={name:/o/}
     dbo.collection("users").deleteMany(where_condition, function(err, res) {
      if (err) throw err;
       console.log("documents deleted successfully");
       //console.log(res);
       console.log("result:",res.result);
       console.log("deleted_count:",res.deletedCount);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the delete_documents.js file.


node delete_documents.js
Output:-
documents deleted successfully
result: { n: 3, ok: 1 }
deleted_count: 3

Nodejs MongoDB find

MongoDB’s document is like a table’s row in RDBMS. to get the documents from the collection through find() or findOne() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

get all the documents through find() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).toArray(function(err, res){
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 } ]

Get the specific key value through projection

If you need a specific key-value then use {keyname:1} through projection


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({},{projection:{name:1}}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’ },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’ },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’ },
{ _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’ } ]

if you do not want _id value in the getting results

If you do not need a specific key-value then use {keyname:0} through projection


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({},{projection:{name:1,_id:0}}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { name: ‘John’ },
{ name: ‘Rom’ },
{ name: ‘Mathew’ },
{ name: ‘Sachin’ } ]

get one document through findOne() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").findOne({}, function(err, res) {
      if (err) throw err;
       console.log("1 document show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
1 document show successfully
result: { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 }

Note:- where_condition is used in the first parameter of the find() or findOne() method.
projection is used in the second parameter of the find() or findOne() method.

Nodejs MongoDB sort

sort() method is used along with the find() method in MongoDB in ascending order or descending order based on keyname (field name).

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

get all the documents in ascending order through {keyname:1} in sort() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).sort({name:1}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 } ]

get all the documents in descending order through {keyname:-1} in sort() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).sort({name:-1}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 } ]

Nodejs MongoDB limit

limit() method is used to get the number of documents in MongoDB.
limit() method works along with the find() method.

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).limit(2).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 } ]

Nodejs MongoDB join

lookup() method is used between 2 or more collections for join in MongoDB. lookup() method used in the aggregate() method.

Suppose you have 2 collections departments and employees

departments collections


[
  { _id: 1, name: "Engineer", status: 1 },
  { _id: 2, name: "Manager", status: 1 },
  { _id: 3, name: "Peon", status: 1 }
]

employees collections


[
  { _id: 1, name: "John", department_id: 1 }
]

Now, get the employee’s details with the department name.

create the collections_join.js file


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("employees").aggregate([
      { $lookup:
         {
           from: 'departments',
           localField: 'department_id',
           foreignField: '_id',
           as: 'departments_details'
         }
       }
      ]).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log(JSON.stringify(res));
       connection_obj.close();
    });
  }catch(err){

    console.log("connection fails");
  
  }

Now, run the collections_join.js file.


node collections_join.js
Output:-
documents show successfully
result: [{“_id”:1,”name”:”John”,”department_id”:1,”departments_details”:[{“_id”:1,”name”:”Engineer”,”status”:1}]}]

Javascript Array

Array is used to store more than one value into single variable.


var arr=["John","Rom","Mathew"];

How to create an Array?


var item=[item1, item2,item3......itemn];

Example:-


var users=["John","Rom","Mathew"];

Creating a Array through new keyword


var users= new Array('John','Rom','Mathew');

First element of Array position is zero.


var users= new Array('John','Rom','Mathew');
console.log(users[0]) //Output:- John

Add element into the Array

push() method:- this method is used to store element into the Array.

Example:-


users=["John","Rom","Mathew"];
users.push("Clerk");
console.log(users);  //Output:- ["John", "Rom", "Mathew", "Clerk"]

Try it Yourself


 numbers=[10,20,30];
 numbers.push(40);
 console.log(numbers) //Output:- [10,20,30,40];

Note:- push() method is used to add element after the last element of the Array.

unshift() method:- this method is also used to add element before the first element of the Array.


users=["John","Rom","Mathew"];
users.unshift("Clerk");
console.log(users);  //Output:- ["Clerk", "John", "Rom", "Mathew"]

Try it Yourself


numbers=[10,20,30];
numbers.unshift(40);
console.log(numbers) //Output:- [40,10,20,30];

Remove element from the Array

pop() method:- this method is used to remove last element from the Array.

Example:-


users=["John","Rom","Mathew"];
users.pop();
console.log(users);  //Output:- ["John", "Rom"]

Try it Yourself


numbers=[10,20,30];
numbers.pop();
console.log(numbers) //Output:- [10,20];

shift() method:- this method is used to remove the first element from the Array.

Example:-


users=["John","Rom","Mathew"];
users.shift();
console.log(users);  //Output:- ["Rom","Mathew"];

Try it Yourself


 numbers=[10,20,30];
 numbers.shift();
 console.log(numbers) //Output:- [20,30];

Modify Array’s element value


users=["John","Rom","Mathew"];
console.log(users);  //Output:- ["John",Rom","Mathew"];

Example:- Now change the Rom to Andrew


 users=["John","Rom","Mathew"];
 users[1]="Andrew";
 console.log(users); // ["John","Andrew","Mathew"];

How to check variable is Array or not?

Array.isArray() function is used to check variable is Array or not.


users=["John","Rom","Mathew"];
var check_array=Array.isArray(users);
console.log(check_array);  //Output: true

Try it Yourself


  var name="John";
  var check_name=Array.isArray(name);
  console.log(check_name);  //Output: false

How to count the Array length?

length is used to count the total number of elements in the Array.


var arr=["John","Rom","Andrew","Smith"]
console.log(arr.length);  //4

Try it Yourself

Sorting Array

You can sort the Array element(which is numeric) Ascending and Descending order.

Ascending Order:-


  var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return a-b;
});
console.log(sort_arr);  
Output:- [3,5,7,10,12,15];

Descending Order:-


 var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return b-a;
});

console.log(sort_arr);  
Output:- [15,12,10,7,5,3];

Javascript String

String can be enclosed in Single Quotes like ‘john’ or Double Quotes like “john” or backtics (which came into ES6) like `john`.


var first_name ='John';
var last_name="Taylor";
var email=`john@abc.com`;

Note:- backtics is basically used to combined variable value and strings.

Example:- Now you add first_name and last_name along with Hello string.


var full_name=`Hello ${first_name} ${last_name}`;
console.log(full_name);  // Output:- John Taylor

Create a String:-

1) String():- You can create string through String function.


var age=35;
var age_string=String(age);  
console.log(age_string);  // Output:- "35"

var bool =true;
var bool_string=String(bool) // Output:- "true"

2) toString():- toString() is used to convert data into string.


var age =35;
var age_string=age.toString(); // Output "35";

var bool =true;
var bool_string=bool.toString() // Output:- "true"

3) creating a String Object through new keyword and it behaves like Object


var string_object = new String("John");
console.log(typeof string_object); //output:- "object" 

Concat two or more strings:- 1) You can concat the two string through + sign


var first_name="John";
var last_name="Taylor";
document.write(first_name + last_name); //Output:- JohnTaylor
document.write(first_name +' '+last_name); //Output:- John Taylor

Try it Yourself

2) You can concat strings through concat() keyword.


var first_name="John";
var last_name="Taylor";
document.write(first_name.concat(last_name)); //Output:- JohnTaylor

Try it Yourself

3) Concat string through backtics


var first_name="John";
var last_name="Taylor";
document.write(`${first_name} ${last_name}`); //Output:- John Taylor

Try it Yourself

trim() method:- this method is used to trim the white space from the string.


var name=" John ";
console.log(name.trim());  //Output:- John

split() method:- It is used to split a string into Array


var str="John went to college";
var str_arr=str.split(" ");
document.write(str_arr[0]);   // Output:- John
document.write(str_arr[1]);   // Output:- went
document.write(str_arr[2]);   // Output:- to
document.write(str_arr[3]);   // Output:- college

Try it Yourself

join() method:- It is used convert Array into String


arr=["John", "went", "to", "college"];
arr_to_string= arr.join("-");
document.write(arr_to_string);  // Output:- John-went-to-college

Try it Yourself

Reverse a string:-


var str="John Taylor"
let rev_string= str.split('').reverse().join('');
document.write(rev_string);  // Output:- rolyaT nhoJ

Try it Yourself

Javascript Variable

JavaScript variable Syntax


(typeOfVariable) variableName = variableValue

Define a variable:- in the below example, variableName name assigned value John


var name="John";

Using a variable:- Now, You can use variable name in the file.


 console.log(name); //John

Note:- If you did not define the variable type then it will work as like var variable,


name="John";
console.log(name); //John

There are two types of JavaScript variable
1) local variable
2) Global variable

1) Local variable:- A variables declared in a function, become LOCAL variable to the function. Local variables have Function scope: They can only be accessed from within the function.


function user() {
  var name = "John";
  console.log(name);
}
	    
user();
console.log(name);  

Note:- When we call console.log(name) after the function user() call then output will be blank.

2) Global Variables:- A variable declared outside a function, becomes GLOBAL variable. A global variable has global scope: All scripts and functions on a web page can access it.


var name = "John";

function myFunction() {

  console.log(name)  
}


Javascript Variable Declaration

var, let and const are used to variable declaration in JavaScript. let and const are introduced in ECMAScript (ES6). before introduced let and const only var is used to variable declaration.
var is used for function scope while let is used to block scoped.

Example:- function scoped


for(var i=1; i<5; i++){
  console.log(i);
 }

console.log("i value is ",i);  //output:- i value is 5

Example:- block scoped


 for(let i=1; i<5; i++){
   console.log(i);  //output:- 1 2 3 4 5
  }

 console.log("i value is ",i); 

Output:- Uncaught ReferenceError: i is not defined

Note:- above example i is block scoped so it will show output in the for loop when you call i after the loop then it will show error.

const declaration:- You can not reassign the value in the const variable.

Example:- If you reassign the value in the premitive datatype then it will show error.


const name="John";
console.log(name); 
Output:-John

Now, change the name from John to Rom.


name="Rom";
console.log(name);


Output:-Uncaught TypeError: Assignment to constant variable.

Example:- If you want to reassign the value into array element then value will be update.


const arr=[1,2];
arr[1]=3;
console.log(arr) //Output:- [1,3]

If we can not reassign in const then why use in for of and for in loop?
it seems that they create a new block scope with each iteration. That would mean that each new index is actually a new variable within a new scope & our constant is never reassigned.


var data=[{name:"John", age:35},{name:"Rom", age:30}] 

for( const element of data){
	
	console.log(element.name);  
} 

Output:- John
Rom

Javascript Datatype

JavaScript has basically two type of datatypes
1) Primitive Datatype
2) Composite Datatype

1) Primitive Datatype:- These type of datatype is immutable and it do not have properties. When you make a copy, it will be a real copy.

Example:- when you reassign a new value to b, the value of b changes, but not of a.


 <script>
 const a = "John";
 let b = a   // this is the copy
 b = "Rom";
 document.write(b) // Rom
 document.write(a) // John
 </script>

Try it Yourself

1) String:- It is basically used to store string value and string value represents through single quote or double quotes.


 var name="John";
 console.log(typeof name);  //string

2) Number:- It is used to store number value.


 var age=35;
 console.log(typeof age);  //number

3) undefined:- A variable that has not value is undefined.


  var name;
  console.log(typeof name); // undefined 

4) Null:- It has null value.


 var nothing = null;
 console.log(nothing);

5) Boolean:- this datatype variable has value true or false.


 var is_loggedin=true;
 console.log(is_loggedin);  //true

 var not_loggedin=false;
 console.log(not_loggedin);  //false

6) Symbol:- It came into ECMAScript6 (ES6). It represents a unique identifier.

2) Composite Datatype:- Object, Array and methods are compositive datatypes. Technically, arrays are also objects, so they behave in the same way. These values are actually stored just once when instantiated, and assigning a variable just creates a pointer (reference) to that value.

Object Example:-


 var users={
      name:"John",
      age:35
        }

 console.log(typeof users) //Object

Array Example:-


 var users=[{
       name:"John",
       age:35
       }]

 console.log(typeof users) //Object

Example:- Now, if we make a copy b = a , and change some nested value in b, it actually changes a’s nested value as well, since a and b actually point to the same thing.


 <script>
 const a = {name:'John'}
 const b=a;
 b.name='Rom';
 document.write(a.name);  //Output:- Rom
 document.write(b.name);  //Output:- Rom
 </script>
 

Try it Yourself

Javascript Array Sorting

You can sort the Array element (which is numeric) in Ascending or Descending order through below code.

Ascending Order:- There are two ways to Sorting in Ascending Order.

1) Array Sorting without function


var arr=[10,5,7,3,12,15];
var temp;
let i;
let j;
for( i=0; i<arr.length; i++)
{
for(j=i; j>0; j--){

  if(arr[j-1] > arr[j]){
        
        temp=arr[j];
        arr[j]=arr[j-1];
        arr[j-1]=temp;

		}
	}
}
console.log(arr);

Try it Yourself

Output:-[3,5,7,10,12,15];

2) Array Sorting with sort() function


  var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return a-b;
});

console.log(sort_arr);  

Try it Yourself

Output:- [3,5,7,10,12,15];

Descending Order:- There are two way in descending Order.

1) Array Sorting without function


var arr=[10,5,7,3,12,15];
var temp;
let i;
let j;
for( i=0; i<arr.length; i++)
{
for(j=i; j>0; j--){

  if(arr[j] > arr[j-1]){
        
        temp=arr[j];
        arr[j]=arr[j-1];
        arr[j-1]=temp;

		}
	}
}
console.log(arr);

Try it Yourself

Output:- [15,12,10,7,5,3];

2) Array Sorting with sort() function


 var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return b-a;
});

console.log(sort_arr);  

Try it Yourself

Output:- [15,12,10,7,5,3];

Javascript Object

Object is used to store multiple values. object has key and value pair.


var obj={name:"John",age:35,sex:"Male"}

You can define multiple objects into the Array. you can say these are Array Object.


var users_details=[{name:"John",age:35,sex:"Male"},
      {name:"Rom",age:30,sex:"Male"},
      {name:"Neena",age:25,sex:"female"}
    ]

define the method into the Object


   var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35,
     full_name: function() {
       return this.first_name + " " + this.last_name;
   }

   }

Note:- full_name is a method in the user_details Object.

get the Object key value

Suppose you have user_details Object and you want to get the key value


     var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35,
     full_name: function() {
       return this.first_name + " " + this.last_name;
   }

   }

Example:- get the user’s full_name and age.


console.log(user_details.full_name);
Output:- John Taylor

get the age of the user


console.log(user_details.age);
Output:- 35

Add key value into the Object

Suppose you have user_details Object


 var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35
   }

Now, you want to add user_id into the user_details Object


 user_details.user_id=1234

Now get the user_details value


console.log(user_details);
Output:-{first_name: “John”, last_name: “Taylor”, age: 35, user_id: 1234}

Try it Yourself

Update key value into the Object

Suppose you have user_details Object


var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35
   }

Now, you have to update age into the user_details Object


 user_details.age=36

Now get the user_details value


console.log(user_details);
Output:-{first_name: “John”, last_name: “Taylor”, age: 36}

Delete the key value from the Object

Syntax:-


delete object.key

Example:- delete the age key value from the Object


     var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35
   }

   delete user_details.age;

   console.log(user_details);

Output:-{first_name: “John”, last_name: “Taylor”}

Try it Yourself

Get the Object key value through for in loop

Syntax:- get the Object value


for (var key in Object){
	
 console.log(Object[key]);

}

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Get the users object value


for (var key in users){
	
	console.log(users[key]);

}
Output:-1
John
Taylor
35

Try it Yourself

How to check Object key is exists or not

Syntax:-



object_name.hasOwnProperty(object_key);  //Output true or false

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Now check the key is exists or not


users.hasOwnProperty("first_name");  //Output true

users.hasOwnProperty("email");  //Output false

Try it Yourself

How to get the Object’s keys

Syntax:-



Object.keys(object_name);  

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Now you want the all users object keys



Object.keys(users);  

Output:-[“id”,”first_name”,”last_name”,”age”]

Try it Yourself

How to get the Object’s values

Syntax:-



Object.values(object_name);  

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Now you want the all users object values



Object.values(users);  

Output:-[1, “John”, “Taylor”, 35]

Try it Yourself

Javascript for loop

for loop is used to get the array value.


for(var i=0; i<5; i++){
	
console.log(i);

}
Output:- 0 1 2 3 4

get the Array value

Suppose you have emp array


var emp=["John","Rom","Mathew","Sachin"];

Now, get the Array value


for(var i=0; i < emp.length; i++){
	
	console.log(emp[i]);

}
Output:- John Rom Mathew Sachin

Note:- emp.length is used to count the number of array element.

get the array element value from last element to first element.


var emp=["John","Rom","Mathew","Sachin"];
for(var i=emp.length-1; i >= 0; i--){
	
	console.log(emp[i]);

}
Output:- Sachin Mathew Rom John

Changes the increment


for(var i=0; i<=10; i=i+2)
{

	console.log(i);
}
Output:- 0 2 4 6 8 10

Javascript for of loop

This loop came into the ES6. It is basically used to get the iteration value from the Array.
Syntax:-


for (variable of iterable) {
  // logic 
}

Example:-


var arr=[10,20,30];
for (var element of arr){
	
 console.log(element);
}
Output:- 10 20 30

Try it Yourself

Note:- you can use var, let and const to get the iteration value.

get the iteration value from the string


var data="John";
for( let element of data){

  console.log(element);

}
Output:- J
o
h
n

get the iteration value from the Array Object


var data=[{name:"John", age:35},{name:"Rom", age:30}]
for( var element of data){
	
	console.log("My name is "+element.name+" and age is "+element.age);

}
Output:-
My name is John and age is 35
My name is Rom and age is 30

Javascript for in loop

It is used to get the iteration value from the object.

Syntax:-


for (variable in iterable) {
  // logic 
}

Example:- get the user object key’s value.


var user ={name:"John",age:35,sex:"Male"}
for(var element in user){
	
 console.log(user[element]);
}
Output:- John 35 Male

Try it Yourself

Get the object’s keys


var user ={name:"John",age:35,sex:"Male"}
for(var element in user){
	
	console.log(element);
}
Output:- name age sex

Javascript While loop

This loop will execute until the condition is given false.

Syntax:-


while(condition){
	
	// logic implement
}

Example:- Now, you have to print the i value until the i value not more than 20.


var i=0;
while(i<=20){
	
	console.log(i);
	i++;
}
Output:-
0
1
.
.

19
20

Example:- Now, you have to print the even i value until the i value not more than 10.


var i=2;
while(i<=10){
  
  if(i%2 ==0){
    console.log(i);
  }
  
  i++;
}
Output:-
2
4
6
8
10

Javascript do while loop

Do while loop run at least once because it checked at the end of the iteration.

Syntax:-


 do{
   // logic
} while(condition)

Example:-


var i=1
do{
	
 console.log(i);
  i++;

}while(i<5);
Output:-
1
2
3
4
5

Javascript Function

Function is basically used to reusable the code. A function is executed when you call it.

Syntax:-


function functionName(parameters){
	
	// logic implement

}

Example:- Suppose you define employeeDetails function which has two parameters name and age.


function employeeDetails(name, age){
  
  console.log("my name is "+name+" and my age is "+age);

}

How to call a function?

You have already defined the function after that you can call the function multiple times based on your requirements.


employeeDetails("John",35);  //my name is John and my age is 35

employeeDetails("Rom",30);  //my name is Rom and my age is 30

What is Function Scoping?

Everything defined in the function can not be access outside the function, this is called function scoping.


function user(){
	
	var emp_name="John";
	console.log(emp_name);  
}
Output:- John

function user(){
	
	var emp_name="John";

}
console.log(emp_name);    
Output:- reference error

What is Immediately Invoke function?

When the function call itself, it is called Immediately Invoke function.

Syntax:-


(function() {
 
// logic

})();

Example:-


(function() {

console.log("Hello");

})();
Output:- Hello

Javascript Function expression

Firstly create a function after that defined into the variable is called function expression.

Syntax:-


var variableName=function(){
}

Note:- You can declare variable through let, var and const according to your requirements.

Example:- Suppose, You create a function and defined into userName variable.


var userName = function() {
  console.log('Hello John');
};

Now, call the userName


userName();
Output:- Hello John

Note:- function expression does not follow Hoisting Rule while Normal function follows the Hoisting Rule.

If you call the function first after that defined the function expression then it will show error.

Example:- Firstly call the userName() function after that defined the userName function expression.


userName();
var userName = function() {
  console.log('Hello John');
};
Output:- Uncaught TypeError: userName is not a function

Normal function follows the Hoisting Rule

Step1:- Firstly call the normal function after that defined userName() function.


userName();
function userName() {
  console.log('Hello John');
};
Output:- Hello John

Step2:- Firstly defined the function after that call the function userName() function.


function userName() {
  console.log('Hello John');
};
userName();
Output:- Hello John

Javascript Constructor function

Constructor function is used to create the Object through new keyword.
First character of the constructor function should be in Capital letters.

Syntax:-


function FunctionName(){
	
	// logic implement

}

var obj = new FunctionName();

Example:- Suppose, You have to create Employee() constructor function.


function Employee(){
	
this.firstName="John";
this.lastName="Mathew";
this.email="john@abc.com";
}

// Now, create the Object

var emp= new Employee();
console.log(emp.firstName);
console.log(emp.lastName);
console.log(emp.email);
Output:- John
Mathew
john@abc.com

Note:- this property reference to the constructor function.

Adding Method in Constructor function

Now you want to add method fullName() in the constructor function.


function Employee(){
     
this.firstName="John";

this.lastName="Mathew";

this.fullName= function(){
	
	return this.firstName+" "+this.lastName;
}

}

Now, create the object



var emp = new Employee();

console.log(emp.fullName())
Output:- John Mathew

Parameters pass in the constructor function

You can pass multiple parameters in the function according your requirements.

Syntax:-


function FunctionName(parameter_1, parameter_2,....parameter_n){
	
	// logic implement

}

var obj = new FunctionName(parameter_1, parameter_2,....parameter_n);

Example:-


function Employee(first_name, last_name){
	
	this.full_name="Welcome "+first_name+" "+last_name;

}

// Now, create the Object

var emp= new Employee("John","Mathew");
console.log(emp.full_name);
Output:- Welcome John Mathew

You can create multiple objects based on your requirements.


var emp= new Employee("Rom","Taylor");
console.log(emp.full_name);
Output:- Welcome Rom Taylor

Adding property into the constructor function object


function Employee(first_name, last_name){
     
this.firstName=first_name;

this.lastName=last_name;

this.fullName= function(){
	
	return this.firstName+" "+this.lastName;
}

}

Suppose, you have to add new property department in the constructor function employee.


var emp = new Employee("John","Mathew");
emp.department="Sales";
console.log(emp.department)
Output:- Sales

Now, you create another object and call the department property then it will show undefined.


var emp2 = new Employee("Rom","Taylor");
console.log(emp2.department)
Output:- undefined

Note:- If you add property after created the object then it will work for same object not other object.

Javascript Prototype

prototype is a most important part of the JavaScript. If you create the object then property and method of this object always inherit from the prototype.


function Student(first_name, last_name, age){
     
this.firstName=first_name;

this.lastName=last_name;

this.age=age;

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1);

Output:-


Student {firstName: "John", lastName: "Mathew", age: 35}
age: 35
firstName: "John"
lastName: "Mathew"
__proto__:
constructor: ƒ Student(first_name, last_name, age)
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

Why the need of the prototype in the property and methods?

Prototype is used to add property or method after created the constructor function.

Suppose you have Student constructor function which have 3 parameters first_name, last_name and age.


function Student(first_name, last_name, age){
     
this.firstName=first_name;

this.lastName=last_name;

this.age=age;

}

Add Property after created the constructor function

Now, you want to add new property class after created the constructor function.

Student.class="MCA";
var stu1 = new Student("John","Mathew",35);
console.log(stu1.class);
Output:- undefined

Now, you will use prototype to add into property after created the constructor function.

Example:-


Student.prototype.class="MCA";
var stu1 = new Student("John","Mathew",35);
console.log(stu1.class);
Output:- MCA

Add method after created the constructor function


Student.address= function(){
	
 return 'Laxmi Nagar, New Delhi';

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1.address);
Uncaught TypeError: stu1.address is not a function

Now, you will add prototype in the method after created the constructor function


Student.prototype.address= function(){
	
	return 'Laxmi Nagar, New Delhi';

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1.address());
Output:- Laxmi Nagar, New Delhi

What is JavaScript

Javascript is a most popular Programming language in the world.
In the starting, JavaScript was used for web browser to build the attractive web pages.
After Node came it is used for Web and mobile App, Real time Networking Application like real chat, etc.

Where JavaScript run?

1) Javascript code write into the script tag.

Syntax:-


<script>
// write code

</script>

Write the code into the script tag


<script>
document.write("Hello JavaScript");
</script>

Try it Yourself

It will show on the browser page.

Output:- Hello JavaScript

2) You can javascript run on the browser console.


> console.log("Hello JavaScript");
Output:- Hello JavaScript

Add two numeric value


<script>
document.write(2+2);
</script>

Try it Yourself

Output:- 4

Add two string


<script>
document.write("Welcome"+" John");
</script>

Try it Yourself

Output:- Welcome John

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)

1) Template Driven form

when you used template driven form then most of the work is done in the component html file like app.component.html or any custom component template file like users.component.html file.
read more

2) Model Driven form (Reactive Form)

when you used Model driven form then most of the work is done in the component class file like app.component.ts or any custom component template file like users.component.ts file.
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.