Learn angular
https://csharp-video-tutorials.blogspot.com/2017/06/angular-2-tutorial-for-beginners_12.html?m=1
https://csharp-video-tutorials.blogspot.com/2018/09/angular-6-tutorial-for-beginners.html
https://csharp-video-tutorials.blogspot.com/2017/12/angular-crud-tutorial.html?m=1
Angular+login+logout
https://jasonwatmore.com/post/2019/06/10/angular-8-user-registration-and-login-example-tutorial
Angular : Angular
is an application design framework
Module: In Angular, a module is a mechanism to group components, directives, pipes
and servit are related, in such a way that can be combined with
other ...
Component: Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Angular components are a subset of directives, always
associated with a template. Unlike other directives, only one component can be instantiated for a given element in a template.
Decorator: Decorator that marks a class as an Angular component and provides configuration metadata that
determines how the component should be processed,
Step 1 :
Tools:
1) node.js
2) editor: vs code
Step 2 :
1) install angular cli using command prompt : npm install -g @angular/cli
https://angular.io/cli
2) to know vertion:
ng
version or ng
v
2)
Creates a new workspace and an initial Angular application.
ng
new employeeprj
ng
n employeeprj
3)
Generates components & classes
ng generate c addemployeecomponent
ng g c addemployeecomponent
ng g class employee
4)
build component
ng
build or ng b
5)
run application
ng serve
Typescript: TypeScript is a programming language developed and maintained by Microsoft.
1)
project -Counter
What Is an Angular Component?
Components are like the basic building block in an Angular application. Components are defined using the @component decorator. A component has a selector , template , style and other properties, using which it specifies the metadata required to process the component.
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Counter';
count: number = 0;
handleIncrease = () => {
this.count = this.count + 1;
};
handleDecrease = () => {
if(this.count < 1){
this.count = 0;
}
else{
this.count = this.count - 1;
}
};
handleReset = () => {
this.count = 0;
};
}
app.component.html
<div class="container">
<header>
<h1>{{title}}</h1>
</header>
<main>
<h2>Current count is : {{count}}</h2>
</main>
<button (click)="handleReset()">Reset Count</button>
<button (click)="handleIncrease()">Increase Count</button>
<button (click)="handleDecrease()">Decrease Count</button>
</div>
Css:
#################### Component STYLE #######################
/* app component container style */
.container {
text-align: center;
display: flex;
justify-content:
start;
align-items: center;
flex-direction:
column;
min-height: 100vh;
color: aliceblue;
margin-top: 30px;
}
/* button style */
button {
color: #fff;
padding: 5px 25px;
margin: 10px;
font-size: 19px;
text-transform:
uppercase;
width: 300px;
border-radius: 15px;
background-color:
#ff00d4;
}
#################### Global STYLE #######################
/* main style for the page and setting background */
body {
margin: 0;
padding: 0;
box-sizing:
border-box;
background-size:
cover;
width: auto;
background-image:
url("./assets/image.jpg");
background-position:
top;
}
o/p
PROJECT FOLDER STRUCTURE
Styles.css
/* You can add global styles to this file, and also import other style files */
body {
margin: 0;
padding: 0;
box-sizing: border-box;
background-size: cover;
width: auto;
background-image: url("./assets/image1.jpg");
background-position: top;
}
Polyfills.ts
import 'zone.js/dist/zone';
main.ts
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));
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angularlearn</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Counter';
count: number = 0;
handleIncrease = () => {
this.count = this.count + 1;
};
handleDecrease = () => {
if(this.count < 1){
this.count = 0;
}
else{
this.count = this.count - 1;
}
};
handleReset = () => {
this.count = 0;
};
}
app.component.html
<div class="container">
<header>
<h1>{{title}}</h1>
</header>
<main>
<h2>Current count is : {{count}}</h2>
</main>
<button (click)="handleReset()">Reset Count</button>
<button (click)="handleIncrease()">Increase Count</button>
<button (click)="handleDecrease()">Decrease Count</button>
</div>
app.component.css
/* app component container style */
.container {
text-align: center;
display: flex;
justify-content: start;
align-items: center;
flex-direction: column;
min-height: 100vh;
color: aliceblue;
margin-top: 30px;
}
/* button style */
button {
color: #fff;
padding: 5px 25px;
margin: 10px;
font-size: 19px;
text-transform: uppercase;
width: 300px;
border-radius: 15px;
background-color: #ff00d4;
}
Installing Bootstrap in Your Angular Project
Step 1 — Installing Bootstrap in Your Angular Project
There are various ways that you can use to install Bootstrap in your project:
- Installing Bootstrap from npm using the
npm install command,
Let’s proceed with the first method. Go back to your command-line interface of project and install Bootstrap via npm as follows:
example
PS D:\Projects\wordsprject> npm install bootstrap
Step 2 — Adding Bootstrap to Angular Using styles.css
We can also use the styles.css file to add the CSS file of Bootstrap to our project.
Open the src/styles.css file of your Angular project and import the bootstrap.css file as follows:
@import "~bootstrap/dist/css/bootstrap.css"
Project2: word generator
app.component.html
<div class="container w-50 mt-5 text-center">
<div class="text-center display-3 m-3 text-white">
word limit :{{limit}}
</div>
<input type="range" min="1" max="50" class="slider form-control-range" value="{{limit}}"
(change)="handleSlideChange($event.target.value)" >
<!-- //button -->
<button class="btn btn-info" (click)="generate()">Generate words</button>
<!-- //dispaly words -->
<div *ngIf="words" class="card card-body">
<p class="display-4">
{{words}}
</p>
</div>
<!-- //button -->
<button class="btn btn-info" (click)="generatecountry()">Generate Random Countrys</button>
<!-- //dispaly countrys -->
<div *ngIf="country" class="card card-body">
<p class="display-4">
{{country}}
</p>
</div>
</div>
app.component.ts
import { Component } from '@angular/core';
import arrayWords from '../utils/words';
import arraycountrys from '../utils/countrys';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'word-generator';
words = '';
country = '';
limit = 0;
limits = 1;
handleSlideChange(newLimit: number) {
debugger;
this.limit = newLimit;
}
generate() {
this.words = arrayWords.slice(0, this.limit).join(' ');
}
generatecountry() {
debugger;
// Math.floor(Math.random() * (max - min + 1) + min);
const randomnumber = Math.floor(Math.random() * (50- 1 + 1) + 1);
this.limits = randomnumber;
this.country = arraycountrys.slice(0, this.limits).join(' ');
}
}
in util folder
words.ts
// some random words
export default [
'busy',
'composition',
'saddle',
'track',
'close',
'aside',
'public',
'break',
'taken',
'bush',
'shelf',
'public',
'string',
'sick',
'member',
'wolf',
'giant',
'government',
'sometime',
'evidence',
'plates',
'though',
'winter',
'spell',
'sure',
'zipper',
'won',
'poem',
'blank',
'rubbed',
'elephant',
'fact',
'wherever',
'store',
'disease',
'loose',
'die',
'count',
'tree',
'hung',
'around',
'alike',
'tide',
'tell',
'motor',
'am',
'pass',
'thus',
'grow',
'imagine',
];
country.ts
is also like above words.ts file array datastyles.css
/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.css";
*,
*::after,
*::before {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
position: relative;
width: 100%;
background-image: url(./assets/bgc.jpg);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
min-height: 100vh;
}
app.component.css
.slider {
appearance: none;
height: 15px;
border-radius: 5%;
background: #919090;
outline: none;
margin: 15px;
}
.slider::-webkit-slider-thumb {
appearance: none;
height: 35px;
width: 35px;
background-color: cyan;
border-radius: 50%;
cursor: pointer;
}
.slider::-moz-range-thumb {
appearance: none;
height: 35px;
width: 35px;
background-color: cyan;
border-radius: 50%;
cursor: pointer;
}
button {
border-radius: 5px;
padding: 10px 35px;
margin: 25px 0;
}
o/p
PROJECT 3:
TIC-TOC-TOI
https://www.npmjs.com/
https://www.npmjs.com/package/ngx-toastr
https://www.npmjs.com/package/@fortawesome/angular-fontawesome
npm install @fortawesome/free-regular-svg-icons
npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
styles.css
/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.css";
@import '~ngx-toastr/toastr';
*,
*::after,
*::before {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
position: relative;
background-image: url(./assets/bgc.jpg);
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { IconComponent } from './components/icon/icon.component';
//font-awesome
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
//Toaster
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
@NgModule({
declarations: [
AppComponent,
IconComponent,
],
imports: [
BrowserModule,
FontAwesomeModule,
BrowserAnimationsModule, // required animations module
ToastrModule.forRoot(), // ToastrModule added
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'tic-tac-toe';
winMessage: string = '';
isCross = false;
itemArray: string[] = new Array(9).fill('empty');
constructor(private toastr: ToastrService) {}
handleClick(itemNumber: number) {
if (this.winMessage) {
return this.toastr.success(this.winMessage);
}
if (this.itemArray[itemNumber] === 'empty') {
this.itemArray[itemNumber] = this.isCross ? 'cross' : 'circle';
this.isCross = !this.isCross;
} else {
return this.toastr.info('Already filled');
}
this.checkIsWinner();
}
checkIsWinner = () => {
// checking winner of the game
if (
this.itemArray[0] === this.itemArray[1] &&
this.itemArray[0] === this.itemArray[2] &&
this.itemArray[0] !== 'empty'
) {
this.winMessage = `${this.itemArray[0]} won`;
} else if (
this.itemArray[3] !== 'empty' &&
this.itemArray[3] === this.itemArray[4] &&
this.itemArray[4] === this.itemArray[5]
) {
this.winMessage = `${this.itemArray[3]} won`;
} else if (
this.itemArray[6] !== 'empty' &&
this.itemArray[6] === this.itemArray[7] &&
this.itemArray[7] === this.itemArray[8]
) {
this.winMessage = `${this.itemArray[6]} won`;
} else if (
this.itemArray[0] !== 'empty' &&
this.itemArray[0] === this.itemArray[3] &&
this.itemArray[3] === this.itemArray[6]
) {
this.winMessage = `${this.itemArray[0]} won`;
} else if (
this.itemArray[1] !== 'empty' &&
this.itemArray[1] === this.itemArray[4] &&
this.itemArray[4] === this.itemArray[7]
) {
this.winMessage = `${this.itemArray[1]} won`;
} else if (
this.itemArray[2] !== 'empty' &&
this.itemArray[2] === this.itemArray[5] &&
this.itemArray[5] === this.itemArray[8]
) {
this.winMessage = `${this.itemArray[2]} won`;
} else if (
this.itemArray[0] !== 'empty' &&
this.itemArray[0] === this.itemArray[4] &&
this.itemArray[4] === this.itemArray[8]
) {
this.winMessage = `${this.itemArray[0]} won`;
} else if (
this.itemArray[2] !== 'empty' &&
this.itemArray[2] === this.itemArray[4] &&
this.itemArray[4] === this.itemArray[6]
) {
this.winMessage = `${this.itemArray[2]} won`;
}
};
reloadGame = () => {
this.winMessage = '';
this.isCross = false;
this.itemArray = new Array(9).fill('empty');
};
}
app.component.html
<div class="container">
<div class="row justify-content-center align-items-center">
<div class="col col-lg-6">
<div class="text-center">
<h1 [hidden]="isCross" class="uppercase text-danger">
Player One Turn
</h1>
<h1 [hidden]="!isCross" class="uppercase text-danger">
Player Two Turn
</h1>
</div>
<div class="grid">
<div *ngFor="let item of itemArray; index as i">
<div class="card">
<div class="card-box box" (click)="handleClick(i)">
<app-icon [iconName]="item"></app-icon>
</div>
</div>
</div>
</div>
</div>
<div class="col col-lg-6 text-center" *ngIf="winMessage">
<h1 class="text-uppercase">Game Over {{ winMessage }}</h1>
<button
(click)="reloadGame()"
class="btn btn-danger text-uppercase pl-5 pr-5"
>
Reload Game
</button>
</div>
</div>
</div>
app.component.css
.container,
.row {
height: 100vh;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 15px;
}
.box {
width: auto;
height: 150px;
display: flex;
justify-content: center;
align-items: center;
}
h1 {
color: aliceblue;
}
iconComponent.ts
import { Component, OnInit,Input } from '@angular/core';
import{faPen,faTimes} from "@fortawesome/free-solid-svg-icons";
import{faCircle} from "@fortawesome/free-regular-svg-icons";
@Component({
selector: 'app-icon',
templateUrl: './icon.component.html',
styleUrls: ['./icon.component.css']
})
export class IconComponent implements OnInit {
@Input() iconName:string;
faPen=faPen;
faTimes=faTimes;
faCircle=faCircle;
constructor() { }
ngOnInit(): void {
}
}
iconComponent.html
<div [ngSwitch]="iconName">
<div *ngSwitchCase="'empty'">
<fa-icon [icon]="faPen" class="icon" ></fa-icon>
</div>
<div *ngSwitchCase="'cross'">
<fa-icon [icon]="faTimes" class="icon text-info"></fa-icon>
</div>
<div *ngSwitchCase="'circle'">
<fa-icon [icon]="faCircle" class="icon text-warning"></fa-icon>
</div>
<div *ngSwitchDefault>
Somthing is not Right!
</div>
</div>
iconComponent.css
.icon {
font-size: 35px;
color: #080000;
font-weight: bolder;
}
o/p
https://rxjs-dev.firebaseapp.com/
TODOS PROJECT:
install bootstrap and fortawesome
Installing Bootstrap in Your Angular Project
Step 1 — Installing Bootstrap in Your Angular Project
There are various ways that you can use to install Bootstrap in your project:
- Installing Bootstrap from npm using the
npm install command,
Let’s proceed with the first method. Go back to your command-line interface of project and install Bootstrap via npm as follows:
example
PS D:\Projects\wordsprject> npm install bootstrap
Step 2 — Adding Bootstrap to Angular Using styles.css
We can also use the styles.css file to add the CSS file of Bootstrap to our project.
Open the src/styles.css file of your Angular project and import the bootstrap.css file as follows:
@import "~bootstrap/dist/css/bootstrap.css"
https://www.npmjs.com/
https://www.npmjs.com/package/ngx-toastr
https://www.npmjs.com/package/@fortawesome/angular-fontawesome
npm install @fortawesome/free-regular-svg-icons
npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {
FontAwesomeModule }
from '@import {
BrowserModule }
from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { TodosComponentComponent } from './component/todos-component/todos-component.component';
import { TodoFormComponentComponent } from './component/todo-form-component/todo-form-component.component';
import { HeaderComponentComponent } from './layout/header-component/header-component.component';
@NgModule({
declarations: [
AppComponent,
TodosComponentComponent,
TodoFormComponentComponent,
HeaderComponentComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FontAwesomeModule,FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
/angular-fontawesome';
import { TodosComponentComponent } from './component/todos-component/todos-component.component';
import { TodoFormComponentComponent } from './component/todo-form-component/todo-form-component.component';
import { HeaderComponentComponent } from './layout/header-component/header-component.component';
@NgModule({
declarations: [
AppComponent,
TodosComponentComponent,
TodoFormComponentComponent,
HeaderComponentComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FontAwesomeModule,FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.tsimport { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Todoapp';
}
app.component.html<ng-container>
<app-header-component></app-header-component>
<div class="container" m-3>
<div class="row">
<div class="col-lg-4">
<img src="../assets/todo.png" class="img-fluid" alt="">
</div>
<div class="col-lg-4">
<app-todo-form-component></app-todo-form-component>
<app-todos-component></app-todos-component>
</div>
</div>
</div>
</ng-container>
styles.css
/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.css";
*,
*::after,
*::before {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
position: relative;
background-color: #222222;
}
todo.tsexport interface Todo {
id: string;
title: string;
isCompleted: boolean;
date: Date;
}
todo.service.ts
import { Injectable } from '@angular/core';
import{of} from 'rxjs';
import {Todo} from '../models/todo';
@Injectable({
providedIn: 'root'
})
export class TodoService {
todos: Todo[];
constructor() {
this.todos = [
{
id: "111",
title: "Learn C++",
isCompleted:true,
date: new Date(),
},
{
id: "222",
title: "Learn React",
isCompleted: true,
date: new Date(),
},
{
id: "333",
title: "Learn Angular",
isCompleted: false,
date: new Date(),
},
];
}
getTodos() {
return of(this.todos);
}
addTodo(todo: Todo) {
this.todos.push(todo);
}
changeStatus(todo: Todo) {
this.todos.map((singleTodo) => {
if (singleTodo.id == todo.id) {
todo.isCompleted = !todo.isCompleted;
}
});
}
deleteTodo(todo: Todo) {
const indexofTodo = this.todos.findIndex(
(currentObj) => currentObj.id === todo.id,
);
this.todos.splice(indexofTodo, 1);
}
}
header-component.component.html<nav class="navbar navbar-dark bg-success">
<a href="#">
<img src="../../../assets/img.png" width="30" height="30" alt="" />
</a>
<span class="navbar-text text-white font-weight-bold">
{{ "LCO TOdo app" | uppercase }}
</span>
</nav>
header-component.component.tsimport { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header-component',
templateUrl: './header-component.component.html',
styleUrls: ['./header-component.component.css']
})
export class HeaderComponentComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
todos-component.tsimport { Component, OnInit } from '@angular/core';
import { TodoService } from "src/app/services/todo.service";
import { Todo } from "../../models/todo";
import { faTrashAlt } from "@fortawesome/free-solid-svg-icons";
@Component({
selector: 'app-todos-component',
templateUrl: './todos-component.component.html',
styleUrls: ['./todos-component.component.css']
})
export class TodosComponentComponent implements OnInit {
faTrashAlt = faTrashAlt;
todos: Todo[];
constructor(private todoService: TodoService) {}
ngOnInit(): void {
this.todoService.getTodos().subscribe((todos) => {
this.todos = todos;
});
}
changeTodoStatus(todo: Todo) {
this.todoService.changeStatus(todo);
}
deleteTodo(todo: Todo) {
this.todoService.deleteTodo(todo);
}
}
todos-component.html
<ul class="list-group w-100" *ngFor="let todo of todos">
<li class="list-group-item d-flex justify-content-between w-100">
<span>
<input
(change)="changeTodoStatus(todo)"
type="checkbox"
[checked]="todo.isCompleted"
/>
</span>
<span [ngClass]="{completedTodo: todo.isCompleted }">
{{ todo.title | uppercase }}
</span>
<span [ngClass]="{completedTodo: todo.isCompleted }">
{{ todo.date | date }}
</span>
<span>
<fa-icon [icon]="faTrashAlt" (click)="deleteTodo(todo)">Trash</fa-icon>
</span>
</li>
</ul>
todos-component.css
.completedTodo {
color: darkgray;
text-decoration: line-through;
}
todo-form-component.ts
import { Component, OnInit } from '@angular/core';
import { TodoService } from "src/app/services/todo.service";
import { v4 as uuidv4 } from "uuid";
import { Todo } from "../../models/todo";
@Component({
selector: 'app-todo-form-component',
templateUrl: './todo-form-component.component.html',
styleUrls: ['./todo-form-component.component.css']
})
export class TodoFormComponentComponent implements OnInit {
todoTitle: string = "";
constructor(private todoService: TodoService) {}
ngOnInit(): void {
}
handleAdd() {
debugger;
const newTodo: Todo = {
id: uuidv4(),
title: this.todoTitle,
isCompleted: false,
date: new Date(),
};
this.todoService.addTodo(newTodo);
console.log(newTodo);
}
}
todo-form-component.html
<div class="input-group mb-3 w-100">
<input type="text" name="todo" [(ngModel)]="todoTitle" placeholder="enter a todo" class="form-control"/>
<div class="input-group-append">
<button (click)="handleAdd()" class="btn btn-primary">Add todo</button>
</div>
</div>
o/p:
Angular Reactive forms:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Registerform</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<!-- CSS only -->
<!-- bootstrap -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossorigin="anonymous"
/>
</head>
<body>
<app-root></app-root>
</body>
</html>
styles.css/* You can add global styles to this file, and also import other style files */
/* You can add global styles to this file, and also import other style files */
body {
background: radial-gradient(rgb(73, 9, 126) 3px, transparent 4px),
radial-gradient(black 3px, transparent 4px),
linear-gradient(#fff 4px, transparent 0),
linear-gradient(
45deg,
transparent 74px,
transparent 75px,
#a4a4a4 75px,
#a4a4a4 76px,
transparent 77px,
transparent 109px
),
linear-gradient(
-45deg,
transparent 75px,
transparent 76px,
#a4a4a4 76px,
#a4a4a4 77px,
transparent 78px,
transparent 109px
),
#fff;
background-size: 109px 109px, 109px 109px, 100% 6px, 109px 109px, 109px 109px;
background-position: 54px 55px, 0px 0px, 0px 0px, 0px 0px, 0px 0px;
}
.container {
margin-top: 10%;
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from "@angular/forms";
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component,tsimport { Component ,OnInit} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { PasswordChecker } from "./custom-validators/password-checker";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'registerform';
registerForm: FormGroup;
submitted = false;
constructor(private formbuilder: FormBuilder){}
ngOnInit() {
this.registerForm = this.formbuilder.group ({
firstName: ["", Validators.required],
lastName: ["", Validators.required],
email: ["", [Validators.required, Validators.email]],
password: ["", [Validators.required, Validators.minLength(6)]],
confirmPassword: ["", Validators.required],
acceptTandC: [false, Validators.requiredTrue],
}, {
validators: PasswordChecker("password", "confirmPassword"),
});
}
get h() {
return this.registerForm.controls;
}
onSubmit() {
this.submitted = true;
if (this.registerForm.invalid) {
return;
}
console.table(this.registerForm.value);
console.table(this.registerForm);
alert("Success Signup\n" + JSON.stringify(this.registerForm.value));
}
onReset() {
this.submitted = false;
this.registerForm.reset();
}
}
password-checker.tsimport { FormGroup } from "@angular/forms";
export function PasswordChecker(controlName: string,CompareControlName: string,)
{
return (formGroup: FormGroup) => {
const password = formGroup.controls[controlName];
const confPassword = formGroup.controls[CompareControlName];
if (password.value !== confPassword.value) {
confPassword.setErrors({ mustmatch: true });
} else {
confPassword.setErrors(null);
}
};
}
app.component.html<div class="container">
<div class="card bg-dark text-white m-3 mt-5">
<h5 class="card-header text-center">
<img src="../assets/logo.jpg" alt="" width="30" height="30" class="mr-2" />
Signup Form
</h5>
<div class="card-body">
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-row">
<div class="form-group col-6">
<label>First Name</label>
<input
type="text"
class="form-control"
formControlName="firstName"
[ngClass]="{ 'is-invalid': submitted && h.firstName.errors }"
/>
<div *ngIf="submitted && h.firstName.errors" class="text-warning">
<div *ngIf="h.firstName.errors.required">
First Name is required
</div>
</div>
</div>
<div class="form-group col-6">
<label>Last Name</label>
<input
formControlName="lastName"
[ngClass]="{ 'is-invalid': submitted && h.lastName.errors }"
type="text"
class="form-control"
/>
<div *ngIf="submitted && h.lastName.errors" class="text-warning">
<div *ngIf="h.lastName.errors.required">
Last Name is required
</div>
</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input
formControlName="email"
[ngClass]="{ 'is-invalid': submitted && h.email.errors }"
type="text"
class="form-control"
/>
<div *ngIf="h.email.touched && h.email.errors" class="text-warning">
<div *ngIf="h.email.errors.required">Email is required</div>
<div *ngIf="h.email.errors.email">
Email must be a valid email address
</div>
</div>
</div>
<ng-container *ngIf="h.email.touched && h.email.errors">
<div *ngIf="h.email.errors.required" class="text-danger">
Value is required.
</div>
</ng-container>
<div class="form-row">
<div class="form-group col">
<label>Password</label>
<input
formControlName="password"
[ngClass]="{ 'is-invalid': submitted && h.password.errors }"
type="password"
class="form-control"
/>
<div
*ngIf="h.password.touched && h.password.errors"
class="text-warning"
>
<div *ngIf="h.password.errors.required">Password is required</div>
<div *ngIf="h.password.errors.minlength">
Password must be at least 6 characters
</div>
</div>
</div>
<div class="form-group col">
<label>Confirm Password</label>
<input
formControlName="confirmPassword"
[ngClass]="{
'is-invalid': submitted && h.confirmPassword.errors
}"
type="password"
class="form-control"
/>
<div
*ngIf="h.confirmPassword.touched && h.confirmPassword.errors"
class="text-warning"
>
<div *ngIf="h.confirmPassword.errors.required">
Confirm Password is required
</div>
<div *ngIf="h.confirmPassword.errors.mustmatch">
Passwords must match
</div>
</div>
</div>
</div>
<div class="form-group form-check">
<input
formControlName="acceptTandC"
[ngClass]="{
'is-invalid': submitted && h.acceptTandC.errors
}"
type="checkbox"
id="acceptTerms"
class="form-check-input"
/>
<label for="acceptTerms" class="form-check-label"
>Accept Terms & Conditions</label
>
<div *ngIf="submitted && h.acceptTandC.errors" class="text-warning">
<div *ngIf="h.acceptTandC.errors.required">
Accept Ts & Cs is required
</div>
</div>
</div>
<div class="text-center">
<button class="btn btn-success btn-lg px-4 mr-3">Register</button>
<button (click)="onReset()" class="btn btn-warning" type="reset">
Reset
</button>
<p class="text white">Value: {{ registerForm.value | json }}</p>
<p class="text white">Value: {{ registerForm.valid | json }}</p>
</div>
</form>
</div>
</div>
</div>
o/p:curd+data+service+api:
################## Global CSS #########################
/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.min.css";
/* for toast importing */
@import "~ngx-toastr/toastr";
/* reset */
*,
*::after,
*::before {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-image: url(./assets/background.jpg);
}
################## app CSS #########################
.app {
min-height: 100vh;
}
################## card CSS #########################
.card {
margin-top: 125px;
}
img {
margin-top: -80px;
}
################## npm install #########################
npm install bootstrap ngx-toastr
npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/angular-fontawesome
styles.css
/* You can add global styles to this file, and also import other style files */
@import "~bootstrap/dist/css/bootstrap.min.css";
/* for toast importing */
@import "~ngx-toastr/toastr";
/* reset */
*,
*::after,
*::before {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
background-image: url(./assets/background.jpg);
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CardComponent } from './components/card/card.component';
//http
import { HttpClientModule } from "@angular/common/http";
//for toast
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { ToastrModule } from "ngx-toastr";
//font Awesome
import { FontAwesomeModule } from "@fortawesome/angular-fontawesome";
@NgModule({
declarations: [
AppComponent,
CardComponent
],
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule, // required animations module
ToastrModule.forRoot(), // ToastrModule added
FontAwesomeModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
userservices.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class UserservicesService {
private url = "https://randomuser.me/api";
constructor(private http:HttpClient) { }
getUser() {
return this.http.get(this.url);
}
}
app.component.css
.app {
min-height: 100vh;
}
app.component.ts
import { Component } from '@angular/core';
import { UserservicesService } from "./service/userservices.service";
import { ToastrService } from "ngx-toastr";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = "random-card";
user: any;
constructor(
private userService: UserservicesService,
private toastr: ToastrService,
) {}
ngOnInit() {
this.userService.getUser().subscribe(
(user: any) => {
console.log(user);
this.user = user.results[0];
},
(err) => {
this.toastr.error(err.status, "OOps");
},
);
}
}
app.component.html
<div class="app p-4 container-fluid">
<div class="row">
<div class="col col-md-4 offset-md-4">
<div class="text-center">
<app-card [user]="user" *ngIf="user; else loadingBlock"></app-card>
<!-- loadingBlock is executed-->
<ng-template #loadingBlock>
<div class="text-center mt-5">
<div
class="spinner-border spinner-grow-mg text-white"
role="status" >
<div class="text-white">
loading....
</div>
</div>
</div>
</ng-template>
</div>
</div>
</div>
</div>
card.component.css.card {
margin-top: 125px;
}
img {
margin-top: -80px;
}
card.component.ts
import { Component, OnInit, Input } from "@angular/core";
import {
faEnvelope,
faMapMarkedAlt,
faPhone,
faDatabase,
} from "@fortawesome/free-solid-svg-icons";
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent implements OnInit {
@Input()user: any;
faEnvelope = faEnvelope;
faMapMarkedAlt = faMapMarkedAlt;
faPhone = faPhone;
faDatabase = faDatabase;
constructor() {}
ngOnInit(): void {
}
}
card.component.html
<div class="card">
<div class="card-body text-center">
<img
width="150"
height="150"
class="rounded-circle img-thumbnail border-danger"
[src]="user.picture?.large"
alt=""
/>
<div class="card-title text-primary">
<h1>
<span class="px-2">{{ user.name?.title }}.</span>
<span class="px-2">{{ user.name?.first }}</span>
<span class="px-2">{{ user.name?.last }}</span>
</h1>
</div>
<div class="card-text">
<fa-icon [icon]="faEnvelope"></fa-icon>
{{ user.email }}
</div>
<div class="card-text">
<fa-icon [icon]="faMapMarkedAlt"></fa-icon>
{{ user.location?.city }} {{ user.location?.state }}
<p>{{ user.location?.street?.number }}</p>
</div>
</div>
</div>
o/p:
Comments
Post a Comment