Phonebook web app

Pls add hacktoberfest accepted tag while merging
pull/923/head
Debarya Pal 3 years ago committed by GitHub
parent 120204995f
commit 22c7e9255f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,6 @@
export class Contact {
id: number = 0
firstName: string = ''
lastName: string = ''
phoneNumber: string = ''
}

@ -0,0 +1,40 @@
<div class="container">
<h2>Add Contact</h2>
<form [formGroup]="addContactForm" (ngSubmit)="onSubmit()">
<div class="form-group my-2">
<label for="firstName">First Name:</label>
<input formControlName="firstName" placeholder="First Name" name="firstName" class="form-control" id="firstName">
<div *ngIf="submitted && addContactForm.controls.firstName.errors" class="error">
<div class="text-danger" *ngIf="addContactForm.controls.firstName.errors.required">
FirstName is required
</div>
</div>
</div>
<div class="form-group my-2">
<label for="lastName">Last Name:</label>
<input formControlName="lastName" placeholder="Last name" name="lastName" class="form-control" id="lastName">
<div *ngIf="submitted && addContactForm.controls.lastName.errors" class="error">
<div class="text-danger" *ngIf="addContactForm.controls.lastName.errors.required">
LastName is required
</div>
</div>
</div>
<div class="form-group my-2 mb-3">
<label for="phoneNumber">Phone Number:</label>
<input type="tel" formControlName="phoneNumber" placeholder="Phone Number" name="phoneNumber" class="form-control" id="phoneNumber">
<div *ngIf="submitted && addContactForm.controls.phoneNumber.errors" class="error">
<div class="text-danger" *ngIf="addContactForm.controls.phoneNumber.errors.required">
Phone is required
</div>
</div>
</div>
<div class="mt-2">
<button class="btn btn-success">Save</button>
<button class="btn btn-danger mx-5" type="reset">Cancel</button>
<a class="btn btn-warning" href="/">Back to List</a>
</div>
  </form>
</div>

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AddContactComponent } from './add-contact.component';
describe('AddContactComponent', () => {
let component: AddContactComponent;
let fixture: ComponentFixture<AddContactComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AddContactComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(AddContactComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

@ -0,0 +1,38 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ContactService } from '../contact.service';
@Component({
selector: 'app-add-contact',
templateUrl: './add-contact.component.html',
styleUrls: ['./add-contact.component.css']
})
export class AddContactComponent implements OnInit {
addContactForm: FormGroup
submitted: boolean = false
constructor(private formBuilder: FormBuilder, private router: Router, private contactService: ContactService) { }
ngOnInit() {
    this.addContactForm = this.formBuilder.group({
id: [],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
phoneNumber: ['', Validators.required]
});
}
onSubmit() {
this.submitted = true
if (this.addContactForm.invalid) {
return
}
this.contactService.createContact(this.addContactForm.value).subscribe(data => {
this.router.navigate(['list-user'])
})
  }
}

@ -0,0 +1,19 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AddContactComponent } from './add-contact/add-contact.component';
import { EditContactComponent } from './edit-contact/edit-contact.component';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'home', component: HomeComponent },
{ path: 'addContact', component: AddContactComponent },
{ path: 'editContact', component: EditContactComponent },
{ path: '**', component: HomeComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

@ -0,0 +1,3 @@
.phoneBook {
background-color: rgb(184, 148, 148);
}

@ -0,0 +1,16 @@
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * * * The content below * * * * * * * * * * * -->
<!-- * * * * * * * * * * is only a placeholder * * * * * * * * * * -->
<!-- * * * * * * * * * * and can be replaced. * * * * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
<!-- * * * * * * * * * Delete the template below * * * * * * * * * * -->
<!-- * * * * * * * to get started with your project! * * * * * * * * -->
<!-- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -->
lass="col-md-7 col-lg-7 mx-auto p-3 mx-auto phoneBook">
<h2 class="text-center p-3">
<i class="fas fa-address-book"></i> Phone Book App
</h2>
<!-- <app-home></app-home> -->
<router-outlet></router-outlet>
</div>

@ -0,0 +1,35 @@
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'PhoneBook-Angular'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('PhoneBook-Angular');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('PhoneBook-Angular app is running!');
});
});

@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'PhoneBook-Angular';
}

@ -0,0 +1,31 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AddContactComponent } from './add-contact/add-contact.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { EditContactComponent } from './edit-contact/edit-contact.component';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AddContactComponent,
EditContactComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
Ng2SearchPipeModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ContactService } from './contact.service';
describe('ContactService', () => {
let service: ContactService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ContactService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

@ -0,0 +1,43 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Contact } from './Contact';
@Injectable({
providedIn: 'root'
})
export class ContactService {
constructor(private http: HttpClient) { }
baseUrl: string = 'http://localhost:3000/contacts'
// get all contact
getContacts() {
return this.http.get<Contact[]>(this.baseUrl)
}
// get contact by id
getContactById(id: number) {
return this.http.get<Contact[]>(this.baseUrl + '/' + id)
}
// get contact by last name
getContactByLastName(lastName: string) {
return this.http.get<Contact[]>(this.baseUrl + '/' + lastName)
}
// create contact
createContact(contact: Contact) {
return this.http.post(this.baseUrl, contact)
}
// modify contact
updateContact(contact: Contact) {
return this.http.put(this.baseUrl + '/' + contact.id, contact)
}
// delete contact
deleteContact(id: number) {
return this.http.delete(this.baseUrl + '/' + id)
}
}

@ -0,0 +1,39 @@
<div class="container">
<h2>Edit Contact</h2>
<form [formGroup]="editContactForm" (ngSubmit)="onSubmit()">
<div class="form-group my-2">
<label for="firstName">First Name:</label>
<input formControlName="firstName" placeholder="First Name" name="firstName" class="form-control" id="firstName">
<div *ngIf="submitted && editContactForm.controls.firstName.errors" class="error">
<div class="text-danger" *ngIf="editContactForm.controls.firstName.errors.required">
FirstName is required
</div>
</div>
</div>
<div class="form-group my-2">
<label for="lastName">Last Name:</label>
<input formControlName="lastName" placeholder="Last name" name="lastName" class="form-control" id="lastName">
<div *ngIf="submitted && editContactForm.controls.lastName.errors" class="error">
<div class="text-danger" *ngIf="editContactForm.controls.lastName.errors.required">
LastName is required
</div>
</div>
</div>
<div class="form-group my-2 mb-3">
<label for="phoneNumber">Phone Number:</label>
<input type="tel" formControlName="phoneNumber" placeholder="Phone Number" name="phoneNumber" class="form-control" id="phoneNumber">
<div *ngIf="submitted && editContactForm.controls.phoneNumber.errors" class="error">
<div class="text-danger" *ngIf="editContactForm.controls.phoneNumber.errors.required">
Phone is required
</div>
</div>
</div>
<div class="my-2">
<button class="btn btn-primary">Update</button>
<a class="btn btn-danger mx-5" href="/">Cancel</a>
</div>
</form>
</div>

@ -0,0 +1,25 @@
import { ComponentFixture, TestBed } from
'@angular/core/testing';
import { EditContactComponent } from
'./edit-contact.component';
describe('EditContactComponent', () => {
let component: EditContactComponent;
let fixture: ComponentFixture<EditContactComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ EditContactComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(EditContactComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

@ -0,0 +1,54 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { Contact } from '../Contact';
import { ContactService } from '../contact.service';
import { first } from 'rxjs/operators';
@Component({
selector: 'app-edit-contact',
templateUrl: './edit-contact.component.html',
styleUrls: ['./edit-contact.component.css']
})
export class EditContactComponent implements OnInit {
contact: Contact
editContactForm: FormGroup
submitted: boolean = false
constructor(private formBuilder: FormBuilder, private router: Router, private contactService: ContactService) { }
ngOnInit() {
let contactId = localStorage.getItem("editContactId")
if (!contactId) {
alert("Invalid action.")
this.router.navigate(['/'])
return
}
this.editContactForm = this.formBuilder.group({
id: [],
phoneNumber: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required]
})
this.contactService.getContactById(+contactId)
.subscribe(data => {
this.editContactForm.setValue(data)
})
}
onSubmit() {
this.submitted = true
if (this.editContactForm.invalid) {
return
}
//returns the first value they receive from the source and closes the observable
this.contactService.updateContact(this.editContactForm.value)
.pipe(first()).subscribe(data => {
this.router.navigate(['/'])
}, error => {
alert(error);
});
}
}

@ -0,0 +1,3 @@
p {
font-size: 0.85rem;
}

@ -0,0 +1,40 @@
<div class="container">
<div class="d-flex flex-row justify-content-between mb-3 container">
<h5 class="m-0 py-2">Contacts</h5>
<button class="btn btn-primary btn-sm py-0 px-4" (click)="addContact()">
<i class="fas fa-plus fa-sm"></i> Add Contact
</button>
</div>
<div class="container input-group form-group my-3">
<div class="input-group-prepend">
<span class="input-group-text py-3" id="basic-addon1">
<span class="fas fa-search fa-lg"></span>
</span>
</div>
<input type="text" name="search" [(ngModel)]="test" class="form-control" placeholder="Search for contact by name..">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
<div class="container">
<ul class="list-group" *ngFor="let contact of contactList | filter:test">
<li class="list-group-item d-flex flex-row justify-content-between align-items-center">
<div>
<h5 class="m-0 pb-2">
{{contact.firstName | titlecase}} {{contact.lastName | titleCase}}
</h5>
<p class="text-muted m-0">
<i class="fas fa-phone-alt"></i> {{contact.phoneNumber}}
</p>
</div>
<div>
<button class="btn btn-success btn-sm mx-2" (click)="editContact(contact)">
<i class="fas fa-pencil-alt"></i>
</button>
<button class="btn btn-danger btn-sm" (click)="deleteContact(contact)">
<i class="fas fa-trash-alt"></i>
</button>
</div>
</li>
</ul>
</div>
</div>

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ HomeComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

@ -0,0 +1,46 @@
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Contact } from '../Contact';
import { ContactService } from '../contact.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
contactList: Contact[] = [];
constructor(private router: Router, private contactService: ContactService) { }
test: string = ''
ngOnInit() {
this.contactService.getContacts().subscribe(data => {
this.contactList = data.sort((a, b) => {
return a.firstName.toLowerCase() > b.firstName.toLowerCase() ? 1 : -1
})
})
}
// Add New Contact
addContact(): void {
this.router.navigate(['addContact'])
}
// Modify Contact
editContact(contact: Contact): void {
localStorage.removeItem("editContactId")
localStorage.setItem("editContactId", contact.id.toString())
this.router.navigate(['editContact'])
}
// Delete Contact
deleteContact(contact: Contact): void {
this.contactService.deleteContact(contact.id).subscribe(data => {
this.contactList = this.contactList.filter(c => c!== contact)
})
}
}

@ -0,0 +1,3 @@
export const environment = {
production: true
};

@ -0,0 +1,16 @@
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error'; // Included with Angular CLI.

Binary file not shown.

After

Width:  |  Height:  |  Size: 948 B

@ -0,0 +1,34 @@
<!doctype html>
<html lang="en">
<head>
<!-- Required Meta Tags-->
<meta charset="utf-8" />
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Find the best courses online!" />
<!-- Title -->
<title>PhoneBook</title>
<!-- Google Fonts -->
<!-- FontAwesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" crossorigin="anonymous">
<!-- Favicons -->
<link rel="icon" type="image/x-icon" href="favicon.ico">
<!-- <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest"> -->
</head>
<body>
<app-root></app-root>
</body>
</html>

@ -0,0 +1,12 @@
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));

@ -0,0 +1,53 @@
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes recent versions of Safari, Chrome (including
* Opera), Edge on the desktop, and iOS and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/

@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */

@ -0,0 +1,26 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
<T>(id: string): T;
keys(): string[];
};
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting(),
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().forEach(context);
Loading…
Cancel
Save