Monday 5 July 2021

Web development with Html and PHP

 HTML Codes:-

We see Lots of Website Like Facebook, Yahoo, Instagram.....Now We will see how this website works and we also try to make this type of websites.......Come ON guys !! Let's ROCK 😈😈 

We use Sublime Text as a text editor, If you want you guys can also use Visual-Code Studio and other software also.


1.Heading:

    <!DOCTYPE html>
<html>
<head>
<title>First Html File</title>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>

<img src="E:\Courses\PHP trainig tedtree\images\1.jpg"height="200" border="2" alt="Image1" title="FirstImage">       **path of my image are given between " " **

</body>
</html>

2.Title & Image:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<img src="E:\Courses\PHP trainig tedtree\images\1.jpeg"height="200" border="2" alt="Image1" title="FirstImage">

</body>
</html>

3.  HyperLink :

  <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

</head>
<body>
<img src="E:\Courses\PHP trainig tedtree\images\Turkey.jpg" height="200" border="2" alt="Image 1" title="Turkey">

<img src="E:\Courses\PHP trainig tedtree\images\Turkey2.jfif" height="200" border="2" alt="Image 1" title="Turkey_Shots">

<br>
<a href="test1.html">Go First Page</a>

</body>
</html>

4.Listing:

Prototype 1:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listing</title>

</head>
<body>
<ol>                   ** OL- ordered list
<li>Kolkata</li>    ** li- number
<li>Delhi</li>
<li>Mumbai</li>
</ol>
 

</body>
</html>

Prototype 2:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listing</title>

</head>
<body>
<ol type="A">
<li>Kolkata</li>
<li>Delhi</li>
<li>Mumbai</li>
</ol>

</body>
</html>

Prototype 3:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listing</title>

</head>
<body>
<ol type="i"> <!-- ol=ordered list -->
<li>Kolkata</li> <!-- li means listing items -->
<li>Delhi</li>
<li>Mumbai</li>
</ol>
<ul>  <!-- ul=unordered list -->
<li>Kolkata</li>
<li>Delhi</li>
<li>Mumbai</li>
</ul>
<ul type="Circle">  <!-- ul=unordered list -->
<li>Kolkata</li>
<li>Delhi</li>
<li>Mumbai</li>
</ul>

</body>
</html>

Table:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table</title>
</head>

<body>
<table>
<thead> 
<tr>
<th>Name</th>
<th>Eamil</th>
</tr>
</thead>
<tbody>
<tr>
<td>Saumitra</td>
<td>saumitra.das@techtreeindia.com</td>
</tr>
<tr>
<td>Anirban</td>
<td>anirban@gmail.com</td>
</tr>
<tr>
<td>Sourav</td>
<td>sourav@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>

With Border:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table</title>
</head>

<body>
<table border="1">
<thead> 
<tr>
<th>Name</th>
<th>Eamil</th>
</tr>
</thead>
<tbody>
<tr>
<td>Saumitra</td>
<td>saumitra.das@techtreeindia.com</td>
</tr>
<tr>
<td>Anirban</td>
<td>anirban@gmail.com</td>
</tr>
<tr>
<td>Sourav</td>
<td>sourav@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>

With Border and cell padding:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table</title>
</head>

<body>
<table border="1" cellpadding="7">
<thead> 
<tr>
<th>Name</th>
<th>Eamil</th>
</tr>
</thead>
<tbody>
<tr>
<td>Saumitra</td>
<td>saumitra.das@techtreeindia.com</td>
</tr>
<tr>
<td>Anirban</td>
<td>anirban@gmail.com</td>
</tr>
<tr>
<td>Sourav</td>
<td>sourav@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>

With Border and cell padding and Cell padding:


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table</title>
</head>

<body>
<table border="1" cellpadding="7" cellspacing="10">
<thead> 
<tr>
<th>Name</th>
<th>Eamil</th>
</tr>
</thead>
<tbody>
<tr>
<td>Saumitra</td>
<td>saumitra.das@techtreeindia.com</td>
</tr>
<tr>
<td>Anirban</td>
<td>anirban@gmail.com</td>
</tr>
<tr>
<td>Sourav</td>
<td>sourav@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>


colspan                     **Colspan- Merging Two or more column in given column
rowspan                       **Rowspan- Merging Two or more row in give row


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Table</title>
</head>

<body>
<table border="1" cellpadding="7" cellspacing="0">
<thead> 
<tr>
<th>Name</th>
<th>Eamil</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">Saumitra</td>
<td>saumitra.das@techtreeindia.com</td>
</tr>
<tr>
<td>sau@gmail.com</td>
<tr>
<td>Anirban</td>
<td>anirban@gmail.com</td>
</tr>
<tr>
<td>Sourav</td>
<td>sourav@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>

Making a Registration Page:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Registration</title>
</head>  

<body>
<h2>User Registration</h2>
<form  name="frm">
<table cellpadding="12">
<tr>
<td>Name</td>
<td><input type="text" name="nm" value="Techtree"></td><br><br>
</tr>
<tr>
<td>Email</td>
<td><input type="Email" name="email_id"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td>Date of Birth</td>
<td><input type="date" name="dob"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gender" value=" Male"> Male
<input type="radio" name="gender" value=" Female"> Female
</td>
</tr>
<tr>
<td>Language</td>
<td><input type="checkbox" name="lang" value="C"> C
<input type="checkbox" name="lang" value="C++">C++
<input type="checkbox" name="lang" value="PHP">PHP 
</td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea name="addr" cols="21" rows="5"></textarea>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select name="city">
<option value="Kolkata">Kolkata</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
</select>
<tr>
<td colspan="2" align="center">
<input type="submit" name="ok" value="Register">
</td>
</table>
</form>
</body>
 


CELLSPACING controls the space between table cells.

CELLPADDING sets the amount of space between the contents of the cell and the cell wall.


WHY PHP??

  • Php is Hypertext Preprocessor.
  • Php is an interpreted language, i.e., there is no need for compilation.
  • Php is a server-side Scripting Language.
  • Php is an Object-Oriented Language.


Easy to Use:
        Code is embedded to HTML.
         Easy to Learn.
         Case sensitive

Cross-Platform:
        Runs on almost any server on several operating systems.
        Wide range of supported database.
          








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

Now fire on GUYZZ for our next big step towards PHP 💣💣

Full form of XAMPP is : 
X (cross-platform), Apache, MySQL, PHP, Perl
For Internal Server and Database in our system, we have to use it.

Now after installing XAMPP start MySql and Apache .



Now create a Folder in -- installation_directory:\xampp\htdocs\php_svt_2

here In this Folder, we will do the next operations.

Using PHP in HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-=8">
<title>First PHP Program</title>
</head>
<body>
<?php
echo "Hello World";   //for Printing line in PHP
?>
</body>
</html>




Save this in our folder php_svt_2  & give it .php extension.

Now open your browser and type: http://localhost/php_svt_2/



You can see this type now open your PHP file and you can see the printed line:




We can start Php code-writing from below::

<?php   ?>  --   Standard type Embedding
<?          ?> --   Short type Embedding
<%       %> --  .net type Embedding

**Short Type does not support Asynchronous Data.
**Standard type embedding supports Asynchronous & synchronous data

Synchronous data: Submitting the Data from Client to the server with Submit Button.
Asynchronous data: Submitting the Data from Client to the server without Submit Button.


<?          ?> 
<%       %> 

 **This two is not active in Real-time server we have to activate it manually, The best option is we use the default type embedding  --   ðŸ˜†

<?php   ?>


To activate other types Embedding : :




Click Config >> PHP(php.ini) >> 


Then from here activate that other types of Embedding.

DEFINING VARIABLE IN PHP :

  $a =25;   ✌
  $b=25.9; ✌




O/P: 


Addition in PHP:




PHP $ and $$ Variables :

$Var is a normal variable with the name var that stores any value like string, integer, float etc.
$$Var is a reference variable that stores the value of the $variable inside it.

Ex-1:
<?php
$x="abc";
$$x=200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>

O/P:

abc
200
200


Different Types of Loops :

  1. While loop
  2. Do-While loop
  3. for loop
  4. for each loop

Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-=8">
<title>Loop</title>
</head>
<body>
<?php
$n=1;
while($n<=10){
echo $n;
$n++;
}

?>
</body>
</html>

O/P: 1 2 3 4 5 6 7 8 9 10


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-=8">
<title>Loop</title>
</head>
<body>
<?php
$n=1;
while($n<=10){
if($n%2==0)
{
echo $n;
}
$n++;
if($n==7){
break;
}
}
?>
</body>
</html>




<!DOCTYPE html>
<html>
<head>
<meta charset="utf-=8">
<title>Loop</title>
</head>
<body>
<?php
do{
echo $n;
$n++;

}while($n<=7);

?>
</body>
</html>

O/P: 1 2 3 4 5 6 7

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-=8">
<title>Loops</title>
</head>
<body>
<?php
for($i=1;$i<11;$i++)
{
echo $i."<br>"
}
?>
</body>
</html>






























Wednesday 26 May 2021

Web App Developement by Angular

What is Angular?

Angular is a TypeScript based, open-source, front-end web application development framework. 

            Angular uses TypeScript as the programming language. It's not Javascript, it's typescript. Typescript is a superset language of Javascript.

So, All Javascript code is valid for typescript code.

        TypeScript code is "transpiled" to regular JavaScript Code. 

TypeScript offers static typing.

Angular is an opinionated web-development framework.


Versions Of Angular:



What is TypeScript?

TypeScript is a superset language of JavaScript. It is just like Javascript with some added sugar.

TypeScript is designed to develop large enterprise apps.

All JavaScript code is valid TypeScript code.

TypeScript is an Object-Oriented Programming Language.

TypeScript Code is compiled down to regular JavaScript Code.


Official Website of TypeScript:

https://www.typescriptlang.org/


Now for Running Angular, we have to install Node Js 

Node JS Installation link:  https://nodejs.org/en/

Now after installation open cmd and type node -v


Now Type npm -v

  • npm is  node package manager
We can see the version of the node package manager.


Now we install VS-Code from their official website


After that, we install Angular CLI- Command Line Interface For Angular.

    The Angular CLI created the Angular Project with all required files and folders. 

    Angular CLI also allows you to build and test your projects using a local development server.

Now To install angular CLI we have to open CMD and type the command:

npm install -g @angular/cli

         -g flag installs the @angular/cli package globally. globally means we can use the angular cli entire our machine not just in a folder.


Now for checking angular version we use the command :

            ng v 


now open cmd and make a folder where we want to create our project. Here we make a website Scribe.

now for making Scribe :

type in cmd- ng new Scribe.

            It installs all files required to make the project...



Now for write code, we have to use Visual Studio Code :

 so in cmd, we write

                               code project name

For our case we write: code Scribe

Then VS code opens:


Now type ng serve --open 

it runs our project in the browser. 

Now here we can see different folders and files.

But for now, we will just work on the src folder,


We start with main.ts file -- This is a TypeScript File. 

            An angular project is divided into modules. Each module can further be divided into more modules then modules can contain components. 

        Components are the basic building block of any application. 

A New Angular Project has one module that further contains just one component. 


The file main.ts is loaded first when the Angular project starts up.


The code we can see in main.ts file:

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

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

                     Now AppModule is the root module that we import from ./app/app.module

app.module.ts this file defines the main module inside the app folder.  This contains the information of the components that we going to use in our Angular Project. 

The Codes of app.module.ts -

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

    As if now there is One Component- AppComponent which we imported from './app.component'

We need to pass the component from a declaration array:

declarations: [
    AppComponent
  ],


The @NgModule decorator converts a regular TS class into an Angular module. 

Basic files of App folder,


As we know about html and css files there is another typescript file.

app.component.ts file...... here all three files are attached together.

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

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


selector: 'app-root'

    we use this app-root to place an HTML tag in anywhere in our Application. 

We also use Bootstrap here. It allows us to help a user interface quickly using Bootstrap. Using BootStrap allow us to build a responsive website.

             BootStrap Download link:

                                              https://getbootstrap.com/      

here a few steps to install BootStrap:


we use npm install bootstrap jquery --save to install bootstrap.  

                --save is used to update the package.json.file  


Now This is our Bootstrap folder.

now we use bootstrap.min.css and bootstrap. min.js

now we go to angular.json file and add

"styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
              "src/styles.css"
            ],
            "scripts": [
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]


Now we ready to use Bootstrap using VS-code.


Practice site for Angular: https://stackblitz.com/


Property Binding & Event Binding:


menu.component.html file :

<h1>
    menu works!<br>
    {{ firstName}} {{ lastName }} <!-- Interpolation-->
</h1>


<div class="container">
    <img [src] = "logo" height="120" width="120" >   <!-- Property Binding -->
    <br>

   <a role ="button" class="btn btn-primary" href = {{google}}>
        Go to Google
   </a>
  

   <button type="button" class="btn btn-danger" [disabled]"disableMyButton" 
(click)"sayHello()" >  <!-- Event Binding -->
       I am Disabled
   </button>
    
   <input type="text" class="form-control" placeholder="Your Name Here" (change)
"log()">

   <br>


   <input type="text" class="form-control" [value]"name">
   <button type="button" class="btn btn-success" (click)"func()">
       Submit
   </button>

</div>


TypeScript file:


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

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

  firstName:string="Pralay";
  lastName:string="Ghosh";

  logo:string="https://angular.io/assets/images/logos/angular/angular.svg";
  
  disableMyButton:boolean=false;
  google:string="https://www.google.com";
  name:string="Internsala";

  constructor() { }

  sayHello(){
    alert("Hello");
  }

  log(){
    console.log("Log called!");
  }

  func(){
    if(this.name=="Internsala")
      this.name="Angular";
    else
      this.name="Internsala";
  }

  ngOnInit(): void {
  }

}


Two Way Data Binding:

We have seen that in one-way data binding any change in the template (view) were not be reflected in the component TypeScript code. To resolve this problem, Angular provides two-way data binding. The two-way binding has a feature to update data from component to view and vice-versa.


Question:

Using two-way binding, do the following:

1. Create two input fields of the type number, say, number1 and number2.

2. Create a third input field, say, sum.

3. Display the sum of number1 and number2 in the sum field.

4. Try doing it with a button to add the numbers.

5. Try doing it without the button. So as the text in the bumber1 and number2 input fields change, the sum should change automatically.

6. Your solution should look something like this.

You can use stackblitz.com to do this exercise.



Html file:

<div class="num1">
  <input type="number" placeholder="First Number"  [(ngModel)]"num1">
  <input type="number" placeholder="Second Number"  [(ngModel)]"num2">
</div>
<div class="sum">
  <input type="number"  [(ngModel)]"num3">

  <button type="button" (click)"clear1()">
  Clear
</button>
  <button type="button" (click)"add()">
  Add
</button>
</div>
<br>
<div class="prt2">
  <input type="number" placeholder="First Number"  [(ngModel)]"num4" (input)"add2()">
  <input type="number" placeholder="Second Number"  [(ngModel)]"num5" (input)"add2()">
</div>
<div class="sum">
  <input type="number"  [(ngModel)]"sum">

  <button type="button" (click)"clear2()">
    Clear
  </button>

</div>


TypeScript File:


import { ComponentVERSION } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  num1number = 23;
  num2number = 34;
  num3number;
  num4number;
  num5number;
  sumnumber;

  constructor() {}

  add() {
    this.num3 = this.num1 + this.num2;
  }
  add2() {
    this.sum = this.num4 + this.num5;
  }

  clear1(){
    this.num1 = undefined;
    this.num2 = undefined;
    this.num3 = undefined;
  }
   clear2(){
    this.num4 = undefined;
    this.num5 = undefined;
    this.sum=undefined;
  }
}


Output:



For Using [(ngModel)]:

 We have to change necessary in our app.module.ts file :

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

.
.
.


@NgModule({
  declarations: [
    AppComponent,
    MenuComponent
  ],
  imports: [
    FormsModule,
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


ngIf Directives:

<div class="container">
    

    <a role="button" class="btn btn-primary" [href]=google *ngIf"showGoogleButton">
        Go to Google
    </a>

    <input type="text" class="form-control" placeholder="Security Code" [(ngModel)]"check">

   <button type="button" class="btn btn-danger" (click)"shouldDisplay()">
        Check!!
    </button>

</div>

 check:string="";
  showGoogleButton:boolean=false;


constructor() { }

shouldDisplay(){
    if(this.check == "Covid"){
      this.showGoogleButtontrue;
    }else{
      this.showGoogleButtonfalse;
    }
      
  }


Listing Array and Access:

Html File:

<div class="container">
    <ul class="list-group">
        <li class="list-group-item">{{friends[0]}}</li>
        <li class="list-group-item">{{friends[1]}}</li>
        <li class="list-group-item">{{friends[2]}}</li>
    </ul>

</div>


Ts File:

 friends:string[] = [];


constructor() { 
    this.friends.push("Amit");
    this.friends.push("Abhirup");
    this.friends.push("Akash");
    this.friends.push("Jigri");

  }


ngFor Directives:

<div class="container">
    <ul class="list-group">
        <li class="list-group-item" *ngFor"let f of friends; let i=index">
{{i+1}}-{{f}}</li>
        </ul>

</div>


ngSwitch Directives:


TypeScript File:

dic:any[]=[{
    "name":"Bob",
    "age":21,
    "country":"UK"
  },
  {
    "name":"Jack",
    "age":25,
    "country":"US"
  },
  {
    "name":"Abhi",
    "age":24,
    "country":"IN"
  },{
    "name":"Merly",
    "age":28,
    "country":"AU"
  },
  {
  "name":"Chintu",
  "age":32,
  "country":"Canada"
}]

Html File:

<div class="container">
    <ul class="list-group">
        <li class="list-group-item" *ngFor"let keys of dic" 
[ngSwitch]="keys.country">
            <div *ngSwitchCase"'IN'" class="text-primary">
{{keys.name}}-{{keys.age}}</div>
            <div *ngSwitchCase"'UK'" class="text-success">
{{keys.name}}-{{keys.age}}</div>
            <div *ngSwitchCase"'US'" class="text-danger">
{{keys.name}}-{{keys.age}}</div>
            <div *ngSwitchCase="'AU'" class="text-warning">
{{keys.name}}-{{keys.age}}</div>
            <div *ngSwitchDefault class="text-dark">
{{keys.name}}-{{keys.age}}</div>
        </li>
    </ul>
</div>


ngClass Directives:


Html File:

<div class="container">
    <ul class"list-group">
        <li class"list-group-item" *ngFor"let people of dic">
            <div [ngClass]"{
                'text-primary':people.country=='IN',
                'text-danger' :people.country== 'AU',
                'text-success' :people.country== 'UK',
                'text-info' :people.country== 'US'

            }">
            {{people.name}}-{{people.country}}
            </div>
        </li>
    </ul>
</div>


TypeScript File:

  dic:any[]=[{
    "name":"Bob",
    "age":21,
    "country":"UK"
  },
  {
    "name":"Jack",
    "age":25,
    "country":"US"
  },
  {
    "name":"Abhi",
    "age":24,
    "country":"IN"
  },{
    "name":"Merly",
    "age":28,
    "country":"AU"
  },
  {
  "name":"Chintu",
  "age":32,
  "country":"Canada"
}]


ngStyle Directives:


Html File:

<div class="container">
    <ul class"list-group">
        <li class"list-group-item" *ngFor"let people of dic">
            <div [ngClass]"{
                'text-primary':people.country=='IN',
                'text-danger' :people.country== 'AU',
                'text-success' :people.country== 'UK',
                'text-info' :people.country== 'US'

            }"
            [ngStyle]"{
                'font-size': '26px',
                'text-decoration': 'underline'
            }"
            >
            {{people.name}}-{{people.country}}
            </div>
        </li>
    </ul>
</div>


**We are working on the same Type-Script File.

Practice Question:

Perform the following tasks. You can use all the Angular Directives you know and any binding.

 1. Create a people array just as explained the lectures. Each person can have information like name, age, and country. You can add additional information if you want.

 2. Display the list of people on the page using ngFor.

 3. Display each item in a different color. You can use any directives that you want. Use Bootstrap classes to add colors.

You can use stackblitz.com to do this exercise.


Answer:

<div class="container">
    <ul class="list-group">
      <li class="list-group-item" *ngFor"let f of people;" [ngSwitch]"f.country">
      <div *ngSwitchCase"'IN'" class"text-danger">
          {{f.name}}-{{f.age}}-{{f.country}}</div>
      <div *ngSwitchCase"'UK'" class"text-success">
            {{f.name}}-{{f.age}}-{{f.country}}</div>
      <div *ngSwitchCase"'AU'" class"text-info">{{f.name}}-{{f.age}}-{{f.country}}</div>
      
    </li>
    </ul>
  </div>


people:any[]=[
  {
    "name" :"Bob",
    "age": 24,
    "country": "IN",
  },
  {
    "name" : "Merly",
    "age":26,
    "country" :"AU",
  },
  {
    "name" :'Pichai',
    "age" :28,
    "country" :"UK",
  }
]



** 1st Create a Component - Signup then in that component we create that form


Creating Forms:

Html File:


<div class="container">
    <h1>
        Signup Form
    </h1>
    <form #signupform = "ngForm" (ngSubmit)"onSubmit(signupform)">
        <div class"form-group">
            <label for"first_name">
                First Name
            </label>
            <input type="text" class="form-control" required name="first_name" 
[(ngModel)]"first_name">
        </div>

        <div class"form-group">
            <label for"last_name">
                Last Name
            </label>
            <input type="text" class="form-control" name="last_name"
 [(ngModel)] ="last_name">
        </div>

        <button type"submit" class="btn btn-success">
            Submit
        </button>



        
    </form>

</div>


TypeScript File:

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

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
  first_name:string"";
  last_name:string"";

  constructor() { }

  onSubmit (signupform){
    console.log(signupform);
  }

  
  ngOnInit(): void {
  }
  


}


app.component.html File:


<app-signup>
  
</app-signup>


Displaying Alert messages based on Certain Condition:


  
<div class"alert alert-danger" *ngIf"signupform.controls['first_name'].touched ==
true && signupform.controls['first_name'].invalid == true">
                First Name is Required
            </div>

Disable Submit button based on Certain Condition :

<button type"submit" class="btn btn-success" [disabled]"signupform.invalid == 
true">
                Submit
            </button>


Creating Reactive Forms:

For using Reactive Forms we have to import reactive-form in app.module.ts file :

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

 imports: [
    FormsModule,
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],


Html File:

<div class"container">
    <div class="row">
        <div class="offset-sm-2 col-sm-8">
            <div class="card text-blank border-0">
                <div class="card-body">
                    <div class="card-title text-center">
                        <h4>Sign Up for Free</h4>
                    </div>
                    
                    <div class="card-text">

                        <form>
                            <div class="form-row">
                                <div class="form-group col-sm-6">
                                    <input type="text" class"form-control"
 placeholder"first_name">

                                </div>

                                <div class="form-group col-sm-6">
                                    <input type="text" class"form-control"
 placeholder="last_name">
                                </div>

                                <div class"alert alert-danger">
                                    First Name & Last Name Required
                                </div>
                            
                            </div>
                            
                            <div class="form-group">
                                <input type="email" class="form-control" 
placeholder="Type your Email Address">
                                <small class="form-text text-muted">
                                    We'll never share your email.
                                </small>
                            </div>

                            <div class"alert alert-danger">
                                Valid Email-Id Required
                            </div>

                            <div class="form-group">
                                <input type="password" class="form-control"
 placeholder="Enter New Password">
                            </div>

                            
                            <div class="form-group">
                                <input type="password" class="form-control" 
placeholder="Confirm Your Password">
                            </div>

                            <div class"alert alert-danger">
                                Please enter a strong password
                            </div>

                            <div class="text-center">
                                <button type"submit" class"btn btn-block 
btn-warning">
                                    Submit
                                </button>
                            </div>
                        </form>
                    </div>



                </div>
            </div>
        </div>
    </div>

</div>



Using form-control :

signup.component.ts File-

importFormBuilderFormGroupFormControlValidators } from '@angular/forms';


export class SignupComponent implements OnInit {
  
  myFormFormGroup;
 

  
  constructor(public fbFormBuilder) {
    this.myForm = this.fb.group({
      firstName:[''],
      lastName:[''],
      email:[''],
      password:[''],
      confirmpassword:['']

    })
   }

signup.component.html File:

<div class"container">
    <div class="row">
        <div class="offset-sm-2 col-sm-8">
            <div class="card text-blank border-0">
                <div class="card-body">
                    <div class="card-title text-center">
                        <h4>Sign Up for Free</h4>
                    </div>
                    
                    <div class="card-text">

                        <form [formGroup]"myForm" (ngSubmit)"onSubmit(myForm)">
                            <div class="form-row">
                                <div class="form-group col-sm-6">
                                    <input type="text" class"form-control" 
placeholder"First Name" [formControl] = "myForm.controls['firstName']" >

                                </div>

                                <div class="form-group col-sm-6">
                                    <input type="text" class"form-control" 
placeholder="Last Name" [formControl] = "myForm.controls['lastName']">
                                </div>

                                <div class"alert alert-danger">
                                    First Name & Last Name Required
                                </div>
                            
                            </div>
                            
                            <div class="form-group">
                                <input type="email" class="form-control" 
placeholder="Type your Email Address" [formControl] = "myForm.controls['email']" >
                                <small class="form-text text-muted">
                                    We'll never share your email.
                                </small>
                            </div>

                            <div class"alert alert-danger">
                                Valid Email-Id Required
                            </div>

                            <div class="form-group">
                                <input type="password" class="form-control" 
placeholder="Enter New Password" [formControl] = "myForm.controls['password']">
                            </div>

                            
                            <div class="form-group">
                                <input type="password" class="form-control" 
placeholder="Confirm Your Password" 
0[formControl] = "myForm.controls['confirmpassword']">
                            </div>

                            <div class"alert alert-danger">
                                Please enter a strong password
                            </div>

                            <div class="text-center">
                                <button type"submit" 
class"btn btn-block btn-warning">
                                    Submit
                                </button>
                            </div>
                        </form>
                    </div>



                </div>
            </div>
        </div>
    </div>

</div>

** Many times <form-control> will not work then open tsconfig.json and make "strictTemplates"false


Using Validators :


signup.component.ts File:

constructor(public fbFormBuilder) {
    this.myForm = this.fb.group({
      firstName:['',[Validators.required]],
      lastName:['',[Validators.required]],
      email:['',[Validators.required]],
      password:['',[Validators.required]],
      confirmpassword:['',[Validators.required]]

    })
   }


Set min-length(8) to password:

constructor(public fbFormBuilder) {
    this.myForm = this.fb.group({
      firstName:['', [Validators.required]],
      lastName:['', [Validators.required]],
      email:['', [Validators.required]],
      password:['', [Validators.requiredValidators.minLength(8)]],
      confirmpassword:['', [Validators.requiredValidators.minLength(8)]]

    })
   }


signup.component.html File:


<div class"container">
    <div class="row">
        <div class="offset-sm-2 col-sm-8">
            <div class="card text-blank border-0">
                <div class="card-body">
                    <div class="card-title text-center">
                        <h4>Sign Up for Free</h4>
                    </div>
                    
                    <div class="card-text">

                        <form [formGroup]"myForm" (ngSubmit)"onSubmit(myForm)">
                            <div class="form-row">
                                <div class="form-group col-sm-6">
                                    <input type="text" class"form-control" 
placeholder"First Name" [formControl] = "myForm.controls['firstName']" >

                                </div>

                                <div class="form-group col-sm-6">
                                    <input type="text" class"form-control" 
placeholder="Last Name" [formControl] = "myForm.controls['lastName']">
                                </div>

                                <div class"alert alert-danger" 
*ngIf"((!myForm.controls['firstName'].valid == true || 
!myForm.controls['lastName'].valid == true)) &&                       
(myForm.controls['firstName'].touched == true || 
myForm.controls['lastName'].touched == true)">
                                    First Name & Last Name Required
                                </div>
                            
                            </div>
                            
                            <div class="form-group">
                                <input type="email" class="form-control"
 placeholder="Type your Email Address" [formControl] = "myForm.controls['email']" >
                                <small class="form-text text-muted">
                                    We'll never share your email.
                                </small>
                            </div>

                            <div class"alert alert-danger" 
*ngIf"!myForm.controls['email'].valid==true && 
myForm.controls['email'].touched==true">
                                Valid Email-Id Required
                            </div>

                            <div class="form-group">
                                <input type="password" 
class="form-control" placeholder="Enter New Password" 
[formControl] = "myForm.controls['password']">
                            </div>

                            
                            <div class="form-group">
                                <input type="password" 
class="form-control" placeholder="Confirm Your Password" 
[formControl] = "myForm.controls['confirmpassword']">
                            </div>

                            <div class"alert alert-danger" 
*ngIf"!myForm.controls['password'].valid==true 
||!myForm.controls['confirmpassword'].valid==true                            
&& myForm.controls['password'].touched==true || 
myForm.controls['confirmpassword'].touched==true">
                                Please enter a strong password
                            </div>

                            <div class="text-center">
                                <button type"submit" 
class"btn btn-block btn-warning">
                                    Submit
                                </button>
                            </div>
                        </form>
                    </div>



                </div>
            </div>
        </div>
    </div>

</div>



Using Custom-Validators :


signup.component.ts File


  constructor(public fbFormBuilder) {
    this.myForm = this.fb.group({
      firstName:['', [Validators.required]],
      lastName:['', [Validators.required]],
      email:['', [Validators.required]],
      password:['', [Validators.requiredValidators.minLength(8)]],
      confirmpassword:['', [Validators.required]]
    }, {
      validator: this.checkPassword("password","confirmpassword"/**checkPassword is a function */
    })
   }

   checkPassword(passwordKey : stringconfirmpasswordKey : string){
     return (group:FormGroup)=>{
       let passwordgroup.controls[passwordKey];
       let confirmpasswordgroup.controls[confirmpasswordKey];
       if(password.value == confirmpassword.value)
       {
         return;
       }else
       {
         confirmpassword.setErrors({
           notEqualtoPassword:true    /**JSON object */
         })
       }


     }
   }



signup.component.html File: 


log the error in form-control:

<div class="text-center">
                                <button type"submit" class"btn btn-block btn-warning" [disabled]"myForm.invalid">
                                    Submit
                                </button>
                            

                               

                            </div>
                        </form>

                        {{ myForm.controls['confirmpassword'].errors | json }} 

                    </div>



Add Firebase :

command: npm install firebase --save


app. module.ts:

import firebase from "firebase/app";
import "firebase/firestore";
import 'firebase/auth';



var firebaseConfig = {
  apiKey: "AIzaSyDG2BYg6Egm94Yg_MuR8NplmPzSQmI-vJQ",
  authDomain: "scribe-cc076.firebaseapp.com",
  projectId: "scribe-cc076",
  storageBucket: "scribe-cc076.appspot.com",
  messagingSenderId: "649522847521",
  appId: "1:649522847521:web:44b754ce7bd09081ed2860",
  measurementId: "G-TDNPT9E4XM"
};
firebase.initializeApp(firebaseConfig);


get the above code from

 



Signing up with  Firebase & Store Values:


import firebase from "firebase/app";
import "firebase/firestore";
import"firebase/auth";


onSubmit(signupform){
     let email:string =signupform.value.email;
     let password:stringsignupform.value.password;
     let firstName:string=signupform.value.firstName;
     let lastName:string=signupform.value.lastName;

     firebase.auth().createUserWithEmailAndPassword(email,password).then(
       (response=> {
         console.log(response);

         let randomNumber = Math.floor(Math.random()*1000)

        response.user.updateProfile({
          displayName: firstName+" "+lastName,
          photoURL: "https://api.adorable.io/avatars" + randomNumber
        })

       }).catch((error)=>{
        console.log(error);

        
       })
  }

Display message for successfull login & Error Login:

  message : string="";
  userError : any;


firebase.auth().createUserWithEmailAndPassword(email,password).then(
       (response=> {
         console.log(response);

         let randomNumber = Math.floor(Math.random()*1000)

        response.user.updateProfile({
          displayName: firstName+" "+lastName,
          photoURL: "https://api.adorable.io/avatars" + randomNumber
        }).then(()=>{
          this.message = "You havebeen signed up successfully. Please Login."
        })

       }).catch((error)=>{
        console.log(error);
        this.userError=error;

        
       })
   }


<div class="alert alert-success" *ngIf"message.length > 0">
                {{ message }}
            </div>
            <div class="alert alert-danger" *ngIf"userError">
                {{ userError }}
            </div>


Make Login Page:

login.component.html 

<div class"container">
    <div class="row">
        <div class="offset-sm-2 col-sm-8">
            <div class="card text-blank">
                <div class="card-body">
                    <div class="card-title text-center">
                        <h4>
                            Login using your Email
                        </h4>
                    </div>
                    <div class="card text">
                        <form>
                            <div class="form-group">
                                <input type="email" class="form-control" 
placeholder="Type Your Email" name="email">

                            </div>

                            <div class="alert alert-danger">
                                Please Provide a Valid Email-Id
                            </div>

                            <div class="form-group">
                                <input type="password" class="form-control" 
placeholder="Type Your Password" name="password">

                            </div>

                            <div class="alert alert-danger">
                                Password is required
                            </div>

                            <div class="text-center">
                                <button type="submit" 
class="btn btn-block btn-warning round">
                                    Submit
                                </button>
                            </div>
                            
                            
                        </form>
    
                    </div>
                    

                </div>
            </div>

            <div class="alert alert-success">
                You havebeen Logged in Successfully.
            </div>
        </div>
    </div>
</div>


login.component.ts

import { ComponentOnInit } from '@angular/core';
import { FormBuilderFormGroupValidators } from '@angular/forms';
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import { error } from 'selenium-webdriver';


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

  myFormFormGroup;
  messagestring="";
  userError:any;



  constructor(public fb:FormBuilder) {
    this.myForm = this.fb.group({
      email:['',Validators.required],
      password:['',Validators.required]
    })
   }



   onSubmit(loginform){
    firebase.auth().signInWithEmailAndPassword(loginform.value.email,loginform.value.password).then((data)=>
    {
      console.log(data);
      this.message="You have Logged in Suceessfully.";
    }).catch((error)=>{
      console.log(error);
      this.userError=error;
    })


  }

  ngOnInit(): void {
  }



}


login.component.html

<div class"container">
    <div class="row">
        <div class="offset-sm-2 col-sm-8">
            <div class="card text-blank">
                <div class="card-body">
                    <div class="card-title text-center">
                        <h4>
                            Login using your Email
                        </h4>
                    </div>
                    <div class="card text">
                        <form [formGroup]"myForm" (ngSubmit)"onSubmit(myForm)">
                            <div class="form-group" >
                                <input type="email" class="form-control"
 placeholder="Type Your Email" name="email" 
[formControl]"myForm.controls['email']">
                            </div>

                            <div class="alert alert-danger" 
*ngIf"myForm.controls['email'].invalid==true  && 
myForm.controls['email'].touched==true">
                                Please Provide a Valid Email-Id
                            </div>

                            <div class="form-group">
                                <input type="password" 
class="form-control" placeholder="Type Your Password" 
name="password" [formControl]"myForm.controls['password']">

                            </div>

                            <div class="alert alert-danger" 
*ngIf"myForm.controls['password'].invalid==true  && 
myForm.controls['password'].touched==true">
                                Password is required
                            </div>

                            <div class="text-center">
                                <button type="submit" 
class="btn btn-block btn-warning round">
                                    Submit
                                </button>
                            </div>
                            
                            
                        </form>
    
                    </div>
                    

                </div>
            </div>

            <div class="alert alert-success" *ngIf"message.length > 0">
                {{ message}}
            </div>

            <div class="alert alert-danger" *ngIf"userError">
                {{ userError }}
            </div>

        </div>
    </div>
</div>



Implementing Service :

making a service command: ng generate service <service name>
ex: ng generate authentication.

import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";


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

  constructor() { }

  login(email:string,password:string){
    return firebase.auth().signInWithEmailAndPassword(email,password)
    }


login.component.ts :

import "firebase/firestore";
import "firebase/auth";
import { AuthService } from "../auth.service";


export class LoginComponent implements OnInit {

  myFormFormGroup;
  messagestring="";
  userError:any;



  constructor(public fb:FormBuilder,public authService:AuthService) {   
    this.myForm = this.fb.group({
      email:['',Validators.required],
      password:['',Validators.required]
    })
   }



   onSubmit(loginform){
    this.authService.login(loginform.value.email,loginform.value.password)
.then((data)=>
    {
      console.log(data);
      this.message="You have Logged in Suceessfully.";
    }).catch((error)=>{
      console.log(error);
      this.userError=error;
    })


  }

  ngOnInit(): void {
  }



}


signup.component.ts:

import firebase from "firebase/app";
import "firebase/firestore";
import"firebase/auth";

import {AuthServicefrom '../auth.service';


export class SignupComponent implements OnInit {
  
  myForm : FormGroup;
  message : string="";
  userError : any;
 

  
  constructor(public fbFormBuilder,public authService:AuthService) {
    this.myForm = this.fb.group({
      firstName:['', [Validators.required]],
      lastName:['', [Validators.required]],
      email:['', [Validators.required]],
      password:['', [Validators.requiredValidators.minLength(8)]],
      confirmpassword:['', [Validators.required]]
    }, {
      validator: this.checkPassword("password","confirmpassword"/**checkPassword is a function */
    })
   }

   checkPassword(passwordKey : stringconfirmpasswordKey : string){
     return (group:FormGroup)=>{
       let passwordgroup.controls[passwordKey];
       let confirmpasswordgroup.controls[confirmpasswordKey];
       if(password.value == confirmpassword.value)
       {
         return;
       }else
       {
         confirmpassword.setErrors({
           notEqualtoPassword:true    /**JSON object */
         })
       }


     }
   }

   onSubmit(signupform){
     let email:string =signupform.value.email;
     let password:stringsignupform.value.password;
     let firstName:string=signupform.value.firstName;
     let lastName:string=signupform.value.lastName;

     firebase.auth().createUserWithEmailAndPassword(email,password).then(
       (response=> {
         
        
        this.message = "You havebeen signed up successfully. Please Login."
      

       }).catch((error)=>{
        console.log(error);
        this.userError=error;

        
       })
   }

  
  
  ngOnInit(): void {
  }
  
  


}



auth. service.ts:


import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import { EmailValidator } from '@angular/forms';


export class AuthService {

  constructor() { }

  login(email:string,password:string){
    return firebase.auth().signInWithEmailAndPassword(email,password)
    }

  signup(email:string,password:string,firstName:string,lastName:string)
  {
    return new Promise<void>((resolvereject)=>{
      firebase.auth().createUserWithEmailAndPassword(email,password)
.then((response)=>
      {

        let randomNumber = Math.floor(Math.random()*1000)

        response.user.updateProfile({
          displayName: firstName+" "+lastName,
          photoURL: "https://api.adorable.io/avatars" + randomNumber
        }).then(() => {
        resolve();
        }).catch((error=>{
        reject();
        })
      }).catch((error=>{
        reject();
      })
    
    })

    
  }
}


Router:

ng generate module app-routing --flat --module=app

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModuleRoutes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';

const routesRoutes = [{
  path: ''component: HomeComponent
},{
  path: 'login'component:LoginComponent
}]; 

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

app.component.html

<router-outlet>
  
</router-outlet>




Create a menu component and Routes with other  components:

<nav class"navbar navbar-expand lg navbar-dark bg-primary">
    <a class="navbar-brand" href="#">
        <img src="assets/Scribe-Logo.png">
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" 
    data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" 
    aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon">

        </span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item" routerLinkActive="active" data-toggle="collapse" 
data-target=".navbar-collapse" *ngIf"!loggedIn">
                <a class="nav-link" routerLink="/home">
                    Home
                </a>
            </li>
            <li class="nav-item" routerLinkActive="active" data-toggle="collapse" 
data-target=".navbar-collapse" *ngIf"loggedIn">
                <a class="nav-link" routerLink="/myblogs">
                    Home
                </a>
            </li>

        </ul> 
        <ul class="navbar-nav ml-auto">
            <li class="nav-item right" *ngIf"!loggedIn" routerLinkActive="active" 
data-toggle="collapse" data-target=".navbar-collapse">
              <button class="btn btn-outline-light px-5" routerLink="/login">
            Login
                </button>
            </li>
            <li class="nav-item right" *ngIf"loggedIn">
                <a class="nav-link" routerLink="/">My Profile</a>
            </li>

            
            <li class="nav-item right" *ngIf"loggedIn">
                <a class="nav-link" routerLink="/" (click)"logout()">Log Out</a>
            </li>
        </ul>

    </div>

</nav>


 loggedIn:boolean=false;






Navigate using Router :

create myblogs component and then go to login. component.ts:


import {Routerfrom '@angular/router';


constructor(public fb:FormBuilder,
public authService:AuthService,public router:Router) {   


onSubmit(loginform){
    this.authService.login(loginform.value.email,loginform.value.password).then((data)=>
    {
      console.log(data);
      this.message="You have Logged in Suceessfully.";

      this.router.navigate([ '\myblogs' ])

app-routing.module.ts:

  path: 'login'component:LoginComponent
},{
  path: 'myblogs'component:MyblogsComponent





Web development with Html and PHP