angular


                                      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 componentsAngular 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';

  countnumber = 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 {

    margin0;

    padding0;

    box-sizingborder-box;

    background-sizecover;

    widthauto;

    background-imageurl("./assets/image1.jpg");

    background-positiontop;

  }

 

 

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';

  countnumber = 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-aligncenter;

  displayflex;

  justify-contentstart;

  align-itemscenter;

  flex-directioncolumn;

  min-height100vh;

  coloraliceblue;

  margin-top30px;

}

 

 

 

/* button style */

button {

  color#fff;

  padding5px 25px;

  margin10px;

  font-size19px;

  text-transformuppercase;

  width300px;

  border-radius15px;

  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

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(newLimitnumber) {
    debugger;
      this.limit = newLimit
  }
   generate() {
    this.words = arrayWords.slice(0this.limit).join(' ');
  }


  generatecountry() {
    debugger;
    // Math.floor(Math.random() * (max - min + 1) + min);
   const randomnumber = Math.floor(Math.random() * (501 + 1) + 1);
    this.limits = randomnumber;
     this.country = arraycountrys.slice(0this.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 {
  padding0;
  margin0;
  box-sizingborder-box;
}

body {
  positionrelative;
  width100%;
  background-imageurl(./assets/bgc.jpg);
  background-positioncenter;
  background-sizecover;
  background-repeatno-repeat;
  min-height100vh;
}

 

app.component.css
.slider {
    appearancenone;
    height15px;
    border-radius5%;
    background#919090;
  
    outlinenone;
    margin15px;
  }
  .slider::-webkit-slider-thumb {
    appearancenone;
    height35px;
    width35px;
    background-colorcyan;
    border-radius50%;
    cursorpointer;
  }
  
  .slider::-moz-range-thumb {
    appearancenone;
    height35px;
    width35px;
    background-colorcyan;
    border-radius50%;
    cursorpointer;
  }
  button {
    border-radius5px;
    padding10px 35px;
    margin25px 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 {
  padding0;
  margin0;
  box-sizingborder-box;
}

body {
  positionrelative;
  background-imageurl(./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';

  winMessagestring = '';
  isCross = false;
  itemArraystring[] = new Array(9).fill('empty');

  constructor(private toastrToastrService) {}

  handleClick(itemNumbernumber) {
    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 {
  height100vh;
}
.grid {
  displaygrid;
  grid-template-columns1fr 1fr 1fr;
  grid-gap15px;
}

.box {
  widthauto;
  height150px;
  displayflex;
  justify-contentcenter;
  align-itemscenter;
}

h1 {
  coloraliceblue;
}

iconComponent.ts

import { ComponentOnInit,Input } from '@angular/core';
import{faPen,faTimesfrom "@fortawesome/free-solid-svg-icons";
import{faCirclefrom "@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-size35px;
    color#080000;
    font-weightbolder;
  }
  
  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

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.ts
import { 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 {
  padding0;
  margin0;
  box-sizingborder-box;
}
body {
  positionrelative;
  background-color#222222;
}


todo.ts
export interface Todo {
    idstring;
    titlestring;
    isCompletedboolean;
    dateDate;
}

todo.service.ts
import { Injectable } from '@angular/core';
import{offrom 'rxjs';
import {Todofrom '../models/todo';
@Injectable({
  providedIn: 'root'
})
export class TodoService {
  todosTodo[];
  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(todoTodo) {
    this.todos.push(todo);
  }

  changeStatus(todoTodo) {
    this.todos.map((singleTodo=> {
      if (singleTodo.id == todo.id) {
        todo.isCompleted = !todo.isCompleted;
      }
    });
  }

  deleteTodo(todoTodo) {
    const indexofTodo = this.todos.findIndex(
      (currentObj=> currentObj.id === todo.id,
    );
    this.todos.splice(indexofTodo1);
  }
}
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.ts
import { ComponentOnInit } 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.ts
import { ComponentOnInit } 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;
  todosTodo[];

  constructor(private todoServiceTodoService) {}

  ngOnInit(): void {
    this.todoService.getTodos().subscribe((todos=> {
      this.todos = todos;
    });
  }

  changeTodoStatus(todoTodo) {
    this.todoService.changeStatus(todo);
  }

  deleteTodo(todoTodo) {
    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 {
  colordarkgray;
  text-decorationline-through;
}


todo-form-component.ts
import { ComponentOnInit } 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 {
 todoTitlestring = ""

  constructor(private todoServiceTodoService) {}

  ngOnInit(): void {
  }

  handleAdd() {
    debugger;
    const newTodoTodo = {
      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:
index.html
<!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 {
    backgroundradial-gradient(rgb(7391263pxtransparent 4px),
      radial-gradient(black 3pxtransparent 4px),
      linear-gradient(#fff 4pxtransparent 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-size109px 109px109px 109px100% 6px109px 109px109px 109px;
    background-position54px 55px0px 0px0px 0px0px 0px0px 0px;
  }
  
  .container {
    margin-top10%;
  }
  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,ts
import { Component ,OnInitfrom '@angular/core';
import { FormBuilderFormGroupValidators } 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';
  registerFormFormGroup;
  submitted = false;
  constructor(private formbuilderFormBuilder){}
  ngOnInit() {
    this.registerForm = this.formbuilder.group ({
      firstName: [""Validators.required],
      lastName: [""Validators.required],
      email: ["", [Validators.requiredValidators.email]],
      password: ["", [Validators.requiredValidators.minLength(6)]],
      confirmPassword: [""Validators.required],
      acceptTandC: [falseValidators.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.ts
import { FormGroup } from "@angular/forms";
export function PasswordChecker(controlNamestring,CompareControlNamestring,) 
{
  return (formGroupFormGroup=> {
    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 {
  padding0;
  margin0;
  box-sizingborder-box;
}

body {
  background-imageurl(./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-height100vh;
  }

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";
  userany;
  constructor(
    private userServiceUserservicesService,
    private toastrToastrService,
  ) {}
  ngOnInit() {
    this.userService.getUser().subscribe(
      (userany=> {
        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-top125px;
  }
  img {
    margin-top-80px;
  }
card.component.ts
import { ComponentOnInitInput } 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()userany;

  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