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.
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 { Component, OnInit } 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 { Component, VERSION } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
num1: number = 23;
num2: number = 34;
num3: number;
num4: number;
num5: number;
sum: number;
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;
shouldDisplay(){
if(this.check == "Covid"){
this.showGoogleButton= true;
}else{
this.showGoogleButton= false;
}
}
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 { Component, OnInit } 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 { FormsModule, ReactiveFormsModule } 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-
import{ FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
export class SignupComponent implements OnInit {
myForm: FormGroup;
constructor(public fb: FormBuilder) {
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 fb: FormBuilder) {
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 fb: FormBuilder) {
this.myForm = this.fb.group({
firstName:['', [Validators.required]],
lastName:['', [Validators.required]],
email:['', [Validators.required]],
password:['', [Validators.required, Validators.minLength(8)]],
confirmpassword:['', [Validators.required, Validators.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 fb: FormBuilder) {
this.myForm = this.fb.group({
firstName:['', [Validators.required]],
lastName:['', [Validators.required]],
email:['', [Validators.required]],
password:['', [Validators.required, Validators.minLength(8)]],
confirmpassword:['', [Validators.required]]
}, {
validator: this.checkPassword("password","confirmpassword") /**checkPassword is a function */
})
}
checkPassword(passwordKey : string, confirmpasswordKey : string){
return (group:FormGroup)=>{
let password= group.controls[passwordKey];
let confirmpassword= group.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:string= signupform.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 { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } 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 {
myForm: FormGroup;
message: string="";
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 {
myForm: FormGroup;
message: string="";
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 {AuthService} from '../auth.service';
export class SignupComponent implements OnInit {
myForm : FormGroup;
message : string="";
userError : any;
constructor(public fb: FormBuilder,public authService:AuthService) {
this.myForm = this.fb.group({
firstName:['', [Validators.required]],
lastName:['', [Validators.required]],
email:['', [Validators.required]],
password:['', [Validators.required, Validators.minLength(8)]],
confirmpassword:['', [Validators.required]]
}, {
validator: this.checkPassword("password","confirmpassword") /**checkPassword is a function */
})
}
checkPassword(passwordKey : string, confirmpasswordKey : string){
return (group:FormGroup)=>{
let password= group.controls[passwordKey];
let confirmpassword= group.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:string= signupform.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>((resolve, reject)=>{
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 { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
const routes: Routes = [{
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 {Router} from '@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