Why is only one of my two modals showing?

I have two modals on the same page. One of them shows just fine. The second one, however, doesn't show. Only the dark "opacity" screen shows, but not the modal itself. I've read other posts and nothing seems to work for me.

I have two modals on the same page. One of them shows just fine. The second one, however, doesn't show. Only the dark "opacity" screen shows, but not the modal itself. I've read other posts and nothing seems to work for me.


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<button type="button" class="btn btn-primary mt-4 ml-2 mb-4" data-toggle="modal" data-target="#modalPublishWithAccount">Usuario registrado quiere publicar</button>

<button type="button" class="btn btn-success mt-4 ml-2 mb-4" data-toggle="modal" data-target="#solicitarArriendoWithAccountModal">Usuario registrado quiere publicar</button>

<!-- MODAL THAT WORKS -->
<div class="modal fade bd-example-modal-lg registration-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" id="modalPublishWithAccount">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content registration-modal-content">
<div class="modal-header registration-modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body modal-body-img registration-modal-body text-center col-lg-8 col-md-8 pb-5 pt-0 mx-auto">
I'm the modal that works
</div>
</div>
</div>
</div>
<!-- /MODAL THAT WORKS -->

<!-- MODAL THAT DOESN'T WORK -->
<div class="modal fade bd-example-modal-lg registration-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" id="solicitarArriendoWithAccountModal" style="z-index:10;">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content registration-modal-content">
<div class="modal-header registration-modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body modal-body-img registration-modal-body text-center col-lg-8 col-md-8 pb-5 pt-0 mx-auto">
I'm the modal that doesn't work
</div>
</div>
</div>
</div>
<!-- /MODAL THAT DOESN'T WORK -->

<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://code.jquery.com/jquery-3.2.1.slim.min.js"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;&lt;/<span class="hljs-name">script</span>&gt;</span>


MEAN Stack Tutorial – Angular 7 CRUD App with Bootstrap 4

MEAN Stack Tutorial – Angular 7 CRUD App with Bootstrap 4

In this article I am going to share with you a MEAN Stack Tutorial, in this MEAN Stack tutorial I am going to create an Angular 7 CRUD App using Bootstrap 4. I will be using Node.js, Express.js, MongoDB for backend and Angular 7 for handling frontend.

Today, I am going to share with you a MEAN Stack Tutorial, in this MEAN Stack tutorial I am going to create an Angular 7 CRUD App using Bootstrap 4. I will be using Node.js, Express.js, MongoDB for backend and Angular 7 for handling frontend.

For the demo purpose, I will create an employee management system using Angular 7 MEAN stack. I will try to cover the essential topic used in CRUD web application development.

In this MEAN stack tutorial, I will share step by step process to build an Angular 7 CRUD (Create, Read, Update, Delete) app from scratch.

Let us understand what does MEAN stack means.

  • Mongo DB – It’s an open-source NoSQL cross-platform document-oriented database.
  • Express JS – It’s a web-based application framework work with Node JS, It helps to build web apps and RESTful APIs.
  • Angular 7 – Its a TypeScript based complete front-end framework developed by Google team.
  • Node JS – It is a free JavaScript run time environment, It executes JavaScript code outside of a browser. It is available for MacOS, Windows, Linux and Unix.

I will be using following plugins and tools to create MEAN Stack app.

Table of Contents

  1. Setup Node JS
  2. Build a Node.JS Backend
  3. Connect MongoDB Database with Angular 7 MEAN Stack App
  4. Create Model with Mongoose JS
  5. Create RESTful APIs using Express JS Routes
  6. Set up Angular 7 MEAN Stack Project
  7. Activate Routing Service in MEAN Stack Angular App
  8. Create Angular 7 Service to Consume RESTful APIs
  9. Register an Employee by Consuming RESTful API in Angualr 7 MEAN Stack App
  10. Show Employees List and Delete Student Object using RESTful API in MEAN Stack App
  11. Edit Employees Data in MEAN Stack Angualr 7 App
#1 Setup Node JS development environment

Follow this link to set up Node JS in your system.

#2 Build a Node.JS Backend

To write the manageable code, we should keep the MEAN Stack backend folder separate. Create a folder by the name of the backend in Angular’s root directory. This folder will handle the backend code of our application, remember it will have the separate node_modules folder from Angular 7.

mkdir backend

Enter the below command to get into the backend folder.

cd backend

Now you are inside the backend folder, run the below command to create the package.json file. This file will have the meta data of your MEAN Stack app, It is also known as the manifest file of any NodeJS project.

npm init -y

– Install and Configure required NPM packages for MEAN Stack app development

Use the below command to install the following node modules.

npm install --save body-parser cors express mongoose
  • body-parser: The body-parser npm module is a JSON parsing middleware. It helps to parse the JSON data, plain text or a whole object.
  • CORS: This is a Node JS package, also known as the express js middleware. It allows enabling CORS with multiple options. It is available through the npm registry.
  • Express.js: Express js is a free open source Node js web application framework. It helps in creating web applications and RESTful APIs.
  • Mongoose: Mongoose is a MongoDB ODM for Node. It allows you to interact with MongoDB database.

Starting a server every time a change is made is a time-consuming task. To get rid of this problem we use nodemon npm module. This package restarts the server automatically every time we make a change. We’ll be installing it locally by using given below command.

npm install nodemon --save-dev

Now, go within the backend folder’s root, create a file by the name of server.js.

touch server.js

Now within the backend > server.js file add the given below code.

let express = require('express'),
   path = require('path'),
   mongoose = require('mongoose'),
   cors = require('cors'),
   bodyParser = require('body-parser'),
   dbConfig = require('./database/db');

// Connecting with mongo db
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
   useNewUrlParser: true
}).then(() => {
      console.log('Database sucessfully connected')
   },
   error => {
      console.log('Database could not connected: ' + error)
   }
)

// Setting up port with express js
const employeeRoute = require('../backend/routes/employee.route')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: false
}));
app.use(cors()); 
app.use(express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));
app.use('/', express.static(path.join(__dirname, 'dist/mean-stack-crud-app')));
app.use('/api', employeeRoute)

// Create port
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
  console.log('Connected to port ' + port)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {
   next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message); // Log error message in our server's console
  if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
  res.status(err.statusCode).send(err.message); // All HTTP requests must have a response, so let's send back an error with its status code and message
});
#3 Connect MongoDB Database with Angular 7 MEAN Stack App

It’s time to connect the MongoDB database with Angular 7 MEAN Stack app, use the below commands to setup MongoDB.

Create a database folder within the backend folder.

mkdir database

Go inside the database folder.

cd database

Then create the backend > database > db.js file inside the database folder.

touch db.js

Include the given below code in backend > database > db.js file.

module.exports = {
  db: 'mongodb://localhost:27017/meandb'
};

Note: meandb is the database name.

Now we need to make the connection between MongoDB and Angular 7 MEAN Stack app. Go to backend > server.js file and include the below code.

let mongoose = require('mongoose');

// Connecting with mongo db
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
   useNewUrlParser: true
}).then(() => {
      console.log('Database sucessfully connected')
   },
   error => {
      console.log('Database could not connected: ' + error)
   }
)
#4 Create Model with Mongoose JS

Let us create the models folder inside the backend folder.

mkdir models

Then i will create the Employee.js file.

touch Employee.js

In this file i will define the Schema for employees collection. My data types are name, email, designation and phoneNumber. Add the given below code in backend > models > Employee.js file.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema
let Employee = new Schema({
   name: {
      type: String
   },
   email: {
      type: String
   },
   designation: {
      type: String
   },
   phoneNumber: {
      type: Number
   }
}, {
   collection: 'employees'
})

module.exports = mongoose.model('Employee', Employee)
#5 Create RESTful APIs using Express JS Routes

Let us create the routes in MEAN Stack Angular 7 app to acess the Employee data through RESTful APIs. I will be using Mongoose.js in our MEAN Stack Tutorial to create, read, update & delete data from MongoDB database.

Create backend > routes > employee.route.js file inside the routes folder.

touch employee.route.js

Add the given below code to create RESTful APIs in MEAN Stack app using mongoose.js.

const express = require('express');
const app = express();
const employeeRoute = express.Router();

// Employee model
let Employee = require('../models/Employee');

// Add Employee
employeeRoute.route('/create').post((req, res, next) => {
  Employee.create(req.body, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
});

// Get All Employees
employeeRoute.route('/').get((req, res) => {
  Employee.find((error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})

// Get single employee
employeeRoute.route('/read/:id').get((req, res) => {
  Employee.findById(req.params.id, (error, data) => {
    if (error) {
      return next(error)
    } else {
      res.json(data)
    }
  })
})

// Update employee
employeeRoute.route('/update/:id').put((req, res, next) => {
  Employee.findByIdAndUpdate(req.params.id, {
    $set: req.body
  }, (error, data) => {
    if (error) {
      return next(error);
      console.log(error)
    } else {
      res.json(data)
      console.log('Data updated successfully')
    }
  })
})

// Delete employee
employeeRoute.route('/delete/:id').delete((req, res, next) => {
  Employee.findOneAndRemove(req.params.id, (error, data) => {
    if (error) {
      return next(error);
    } else {
      res.status(200).json({
        msg: data
      })
    }
  })
})

module.exports = employeeRoute;

We have set up our MEAN Stack Angular 7 app’s backend using Node js, Express js, Angualr 7 and MongoDB.

We have to start 3 servers in our app to start the development in MEAN Stack Angualr 7 app.

Start Angular 7 Server

ng serve

Start Nodemon Server
In order to start nodemon server, first enter into the backend folder using given below command.

cd backend

Then run the following command to start the nodemon server.

nodemon server

You’ll get the following output in your terminal.

# [nodemon] 1.18.6
# [nodemon] to restart at any time, enter `rs`
# [nodemon] watching: *.*
# [nodemon] starting `node server.js`
# Connected to port 4000
# Database sucessfully connected

Start MongoDB Server
Open the new terminal enter into the backend folder then use the below command to start the mongoDB server.

mongod

You can access your API route on given below url, here you can check your data.

Check your Angular frontend on – http://localhost:4200

You can check your api url on – http://localhost:4000/api

MEAN Stack App RESTful APIs

We have successfully created APIs to handle CRUD operations in our MEAN Stack app.

To test the REST API you must use the below command.

curl -i -H "Accept: application/json" localhost:4000/api

Given below output indicates that your REST API is ready to go.

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 2
ETag: W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Date: Sat, 11 May 2019 17:06:09 GMT
Connection: keep-alive
#6 Set up Angular 7 MEAN Stack Project

Install Angular CLI
Angular project is developed using Angular CLI, so before setting up Angular 7 project. You must have Angular CLI installed in your system. Hit the given below command to install the Angular CLI, ignore if Angular CLI is already installed.

npm install @angular/cli -g

Let us install Angular 7 project, run the following command.

ng new mean-stack-crud-app

Angular CLI asks for your choices while setting up the project…

Would you like to add Angular routing?
Select y and Hit Enter.

Which stylesheet format would you like to use? (Use arrow keys)
Choose CSS and hit Enter

Your Angular project is installed now get into the project directory.

cd mean-stack-crud-app

If using visual studio code editor then use the below cmd to open the project.

code .

For this demo Angular 7 MEAN stack tutorial, I will use Bootstrap 4 for creating employee management system. Use the following cmd to install Bootstrap 4.

npm install bootstrap

Then, Go to angular.json file and add the below code in “styles”: [ ] array like given below.

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

Generate components in Angular 7 app.
In order to manage components i will keep all the components in components folder, use the below cmd to generate components in Angular 7.

ng g c components/employee-create
ng g c components/employee-edit
ng g c components/employee-list

Your Angular 7 app has been set up for MEAN Stack development. enter the below command to run the project.

ng serve
#7 Activate Routing Service in MEAN Stack Angular App

In order to navigate between multiple components, we must set up routing service in our app. Now if you remember while setting up an Angular project, CLI asked this question “Would you like to add Angular routing?”. We selected yes, it automatically created app-routing.module.tsand registered in src > app > app.module.ts file.

Include the below code to enable routing service in Angular app.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { EmployeeCreateComponent } from './components/employee-create/employee-create.component';
import { EmployeeListComponent } from './components/employee-list/employee-list.component';
import { EmployeeEditComponent } from './components/employee-edit/employee-edit.component';

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'create-employee' },
  { path: 'create-employee', component: EmployeeCreateComponent },
  { path: 'edit-employee/:id', component: EmployeeEditComponent },
  { path: 'employees-list', component: EmployeeListComponent }  
];

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

export class AppRoutingModule { }

To enable routing service include the below code in app.component.ts file.

<nav>
  <a routerLinkActive="active" routerLink="/employees-list">View Employees</a>
  <a routerLinkActive="active" routerLink="/create-employee">Add Employee</a>
</nav>

<router-outlet></router-outlet>

#8 Create Angular 7 Service to Consume RESTful APIs

To consume RESTful API in MEAN Stack Angualr 7 app, we need to create a service file. This service file will handle Create, Read, Update and Delete operations.

Before we create Angular 7 service in MEAN Stack app to consume RESTful APIs, We need to do 2 following things:

– Configure the HttpClientModule

We need to import HttpClientModule service in app.module.ts file.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule
   ]
})

You’ve successfully placed the HttpClientModule in your Angular app.

– Create Employee Model File

Create src > model > employee.ts file.

ng g cl model/Employee

Add the following code in it.

export class Employee {
   name: string;
   email: string;
   designation: string;
   phoneNumber: number;
}

Create Angular 7 Service

Use the given below cmd to create Angular 7 Service file to manage CRUD operations in MEAN Stack Angular 7 app.

ng g s service/api

Now go to src > app > service > api.service.ts file and add the below code.

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class ApiService {

  baseUri:string = 'http://localhost:4000/api';
  headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private http: HttpClient) { }

  // Create
  createEmployee(data): Observable<any> {
    let url = `${this.baseUri}/create`;
    return this.http.post(url, data)
      .pipe(
        catchError(this.errorMgmt)
      )
  }

  // Get all employees
  getEmployees() {
    return this.http.get(`${this.baseUri}`);
  }

  // Get employee
  getEmployee(id): Observable<any> {
    let url = `${this.baseUri}/read/${id}`;
    return this.http.get(url, {headers: this.headers}).pipe(
      map((res: Response) => {
        return res || {}
      }),
      catchError(this.errorMgmt)
    )
  }

  // Update employee
  updateEmployee(id, data): Observable<any> {
    let url = `${this.baseUri}/update/${id}`;
    return this.http.put(url, data, { headers: this.headers }).pipe(
      catchError(this.errorMgmt)
    )
  }

  // Delete employee
  deleteEmployee(id): Observable<any> {
    let url = `${this.baseUri}/delete/${id}`;
    return this.http.delete(url, { headers: this.headers }).pipe(
      catchError(this.errorMgmt)
    )
  }

  // Error handling 
  errorMgmt(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }

}

We have created Angular 7 service file to handle CRUD operations in our app, now go to app.module.ts file and import this service and add into the providers array like given below.

import { ApiService } from './service/api.service';

@NgModule({
  providers: [ApiService]
})
#9 Register an Employee by Consuming RESTful API in Angualr 7 MEAN Stack App

To register an employee we will use Angular 7 service and RESTful APIs. I’ve used Reactive Forms to register an employee. We are also covering Reactive forms validations in our Angular 7 MEAN Stack app tutorial.

Check out this detailed article on Reactive Forms Validation in Angular 6 | 7

Go to components > employee-create > employee-create.component.ts file and add the following code.

import { Router } from '@angular/router';
import { ApiService } from './../../service/api.service';
import { Component, OnInit, NgZone } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-employee-create',
  templateUrl: './employee-create.component.html',
  styleUrls: ['./employee-create.component.css']
})

export class EmployeeCreateComponent implements OnInit {  
  submitted = false;
  employeeForm: FormGroup;
  EmployeeProfile:any = ['Finance', 'BDM', 'HR', 'Sales', 'Admin']

  constructor(
    public fb: FormBuilder,
    private router: Router,
    private ngZone: NgZone,
    private apiService: ApiService
  ) { 
    this.mainForm();
  }

  ngOnInit() { }

  mainForm() {
    this.employeeForm = this.fb.group({
      name: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-][email protected][a-z0-9.-]+\.[a-z]{2,3}$')]],
      designation: ['', [Validators.required]],
      phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    })
  }

  // Choose designation with select dropdown
  updateProfile(e){
    this.employeeForm.get('designation').setValue(e, {
      onlySelf: true
    })
  }

  // Getter to access form control
  get myForm(){
    return this.employeeForm.controls;
  }

  onSubmit() {
    this.submitted = true;
    if (!this.employeeForm.valid) {
      return false;
    } else {
      this.apiService.createEmployee(this.employeeForm.value).subscribe(
        (res) => {
          console.log('Employee successfully created!')
          this.ngZone.run(() => this.router.navigateByUrl('/employees-list'))
        }, (error) => {
          console.log(error);
        });
    }
  }

}

Go to employee-create.component.html add the following code.

<div class="row justify-content-center">
  <div class="col-md-4 register-employee">
    <!-- form card register -->
    <div class="card-body">
      <form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="inputName">Name</label>
          <input class="form-control" type="text" formControlName="name">
          <!-- error -->
          <div class="invalid-feedback" *ngIf="submitted && myForm.name.errors?.required">
            Name is required.
          </div>
        </div>

        <div class="form-group">
          <label for="inputEmail3">Email</label>
          <input class="form-control" type="text" formControlName="email">
          <!-- error -->
          <div class="invalid-feedback" *ngIf="submitted && myForm.email.errors?.required">
            Enter your email.
          </div>
          <div class="invalid-feedback" *ngIf="submitted && myForm.email.errors?.pattern">
            Enter valid email.
          </div>
        </div>

        <div class="form-group">
          <label for="inputPassword3">Designation</label>
          <select class="custom-select form-control" (change)="updateProfile($event.target.value)"
            formControlName="designation">
            <option value="">Choose...</option>
            <option *ngFor="let employeeProfile of EmployeeProfile" value="{{employeeProfile}}">{{employeeProfile}}
            </option>
          </select>
          <!-- error -->
          <div class="invalid-feedback" *ngIf="submitted && myForm.designation.errors?.required">
            Choose designation.
          </div>
        </div>

        <div class="form-group">
          <label for="inputVerify3">Mobile No</label>
          <input class="form-control" type="text" formControlName="phoneNumber">
          <!-- error -->
          <div class="invalid-feedback" *ngIf="submitted && myForm.phoneNumber.errors?.required">
            Enter your phone number.
          </div>
          <div class="invalid-feedback" *ngIf="submitted && myForm.phoneNumber.errors?.pattern">
            Enter Numbers Only
          </div>
        </div>

        <div class="form-group">
          <button class="btn btn-success btn-lg btn-block" type="submit">Register</button>
        </div>
      </form>

    </div>
  </div><!-- form card register -->
</div>
#10 Show Employees List and Delete Student Object using RESTful API in MEAN Stack App

I will show the Employees list using RESTful APIs and Angular 7 service. Go to src/app/components/employee-list/employee-list.component.ts file and include the below code.

import { Component, OnInit } from '@angular/core';
import { ApiService } from './../../service/api.service';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})

export class EmployeeListComponent implements OnInit {

  Employee:any = [];

  constructor(private apiService: ApiService) { 
    this.readEmployee();
  }

  ngOnInit() {}

  readEmployee(){
    this.apiService.getEmployees().subscribe((data) => {
     this.Employee = data;
    })    
  }

  removeEmployee(employee, index) {
    if(window.confirm('Are you sure?')) {
        this.apiService.deleteEmployee(employee._id).subscribe((data) => {
          this.Employee.splice(index, 1);
        }
      )    
    }
  }

}

To display employees list open the src/app/components/employee-list/employee-list.component.html file and add the following code in it.

<div class="container">
  <!-- No data message -->
  <p *ngIf="Employee.length <= 0" class="no-data text-center">There is no employee added yet!</p>

  <!-- Employee list -->
  <table class="table table-bordered" *ngIf="Employee.length > 0">
    <thead class="table-success">
      <tr>
        <th scope="col">Employee ID</th>
        <th scope="col">Name</th>
        <th scope="col">Email</th>
        <th scope="col">Designation</th>
        <th scope="col">Phone No</th>
        <th scope="col center">Update</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let employee of Employee; let i = index">
        <th scope="row">{{employee._id}}</th>
        <td>{{employee.name}}</td>
        <td>{{employee.email}}</td>
        <td>{{employee.designation}}</td>
        <td>{{employee.phoneNumber}}</td>
        <td class="text-center edit-block">
          <span class="edit" [routerLink]="['/edit-employee/', employee._id]">
            <button type="button" class="btn btn-success btn-sm">Edit</button>
          </span>
          <span class="delete" (click)="removeEmployee(employee, i)">
            <button type="button" class="btn btn-danger btn-sm">Delete</button>
          </span>
        </td>
      </tr>
    </tbody>
  </table>
</div>
#11 Edit Employees Data in MEAN Stack Angualr 7 App

In order to edit employees data we need to add the following code in src/app/components/employee-edit/employee-edit.component.html file.

 <div class="row justify-content-center">
   <div class="col-md-4 register-employee">
     <!-- form card register -->
     <div class="card card-outline-secondary">
       <div class="card-header">
         <h3 class="mb-0">Edit Employee</h3>
       </div>
       <div class="card-body">
         <form [formGroup]="editForm" (ngSubmit)="onSubmit()">

           <div class="form-group">
             <label for="inputName">Name</label>
             <input class="form-control" type="text" formControlName="name">
             <div class="invalid-feedback" *ngIf="submitted && myForm.name.errors?.required">
               Name is required.
             </div>
           </div>
           <div class="form-group">
             <label for="inputEmail3">Email</label>
             <input class="form-control" type="text" formControlName="email">
             <!-- error -->
             <div class="invalid-feedback" *ngIf="submitted && myForm.email.errors?.required">
               Enter your email.
             </div>
             <div class="invalid-feedback" *ngIf="submitted && myForm.email.errors?.pattern">
               Enter valid email.
             </div>
           </div>

           <div class="form-group">
             <label for="inputPassword3">Designation</label>
             <select class="custom-select form-control" (change)="updateProfile($event.target.value)"
               formControlName="designation">
               <option value="">Choose...</option>
               <option *ngFor="let employeeProfile of EmployeeProfile" value="{{employeeProfile}}">{{employeeProfile}}
               </option>
             </select>
             <!-- error -->
             <div class="invalid-feedback" *ngIf="submitted && myForm.designation.errors?.required">
               Choose designation.
             </div>
           </div>

           <div class="form-group">
             <label for="inputVerify3">Mobile No</label>
             <input class="form-control" type="text" formControlName="phoneNumber">
             <!-- error -->
             <div class="invalid-feedback" *ngIf="submitted && myForm.phoneNumber.errors?.required">
               Enter your phone number.
             </div>
             <div class="invalid-feedback" *ngIf="submitted && myForm.phoneNumber.errors?.pattern">
               Enter Numbers Only
             </div>
           </div>

           <div class="form-group">
             <button class="btn btn-success btn-lg btn-block" type="submit">Update</button>
           </div>
         </form>
       </div>
     </div><!-- form  -->
   </div>
 </div>

To edit employees data we need to add the following code in src/app/components/employee-edit/employee-edit.component.ts file.

import { Employee } from './../../model/Employee';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { ApiService } from './../../service/api.service';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";

@Component({
  selector: 'app-employee-edit',
  templateUrl: './employee-edit.component.html',
  styleUrls: ['./employee-edit.component.css']
})

export class EmployeeEditComponent implements OnInit {
  submitted = false;
  editForm: FormGroup;
  employeeData: Employee[];
  EmployeeProfile: any = ['Finance', 'BDM', 'HR', 'Sales', 'Admin']

  constructor(
    public fb: FormBuilder,
    private actRoute: ActivatedRoute,
    private apiService: ApiService,
    private router: Router
  ) {}

  ngOnInit() {
    this.updateEmployee();
    let id = this.actRoute.snapshot.paramMap.get('id');
    this.getEmployee(id);
    this.editForm = this.fb.group({
      name: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-][email protected][a-z0-9.-]+\.[a-z]{2,3}$')]],
      designation: ['', [Validators.required]],
      phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    })
  }

  // Choose options with select-dropdown
  updateProfile(e) {
    this.editForm.get('designation').setValue(e, {
      onlySelf: true
    })
  }

  // Getter to access form control
  get myForm() {
    return this.editForm.controls;
  }

  getEmployee(id) {
    this.apiService.getEmployee(id).subscribe(data => {
      this.editForm.setValue({
        name: data['name'],
        email: data['email'],
        designation: data['designation'],
        phoneNumber: data['phoneNumber'],
      });
    });
  }

  updateEmployee() {
    this.editForm = this.fb.group({
      name: ['', [Validators.required]],
      email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-][email protected][a-z0-9.-]+\.[a-z]{2,3}$')]],
      designation: ['', [Validators.required]],
      phoneNumber: ['', [Validators.required, Validators.pattern('^[0-9]+$')]]
    })
  }

  onSubmit() {
    this.submitted = true;
    if (!this.editForm.valid) {
      return false;
    } else {
      if (window.confirm('Are you sure?')) {
        let id = this.actRoute.snapshot.paramMap.get('id');
        this.apiService.updateEmployee(id, this.editForm.value)
          .subscribe(res => {
            this.router.navigateByUrl('/employees-list');
            console.log('Content updated successfully!')
          }, (error) => {
            console.log(error)
          })
      }
    }
  }

}

We have created basic MEAN Stack Angular 7 CRUD app, now enter the below command to start your project on the browser.

ng serve
Conclusion

Finally, we are done for this MEAN Stack Tutorial using Angular 7 and Bootstrap 4. I have tried to highlight every essential topic in this tutorial. However, if you have skipped anything you can check out my GitHub repo. I believe this MEAN Stack tutorial will help you to create your first MEAN stack app.

Front-end Developer Handbook 2019

Front-end Developer Handbook 2019

Sponsored by Frontend Masters, advancing your skills with in-depth, modern front-end engineering courses

Sponsored by Frontend Masters, advancing your skills with in-depth, modern front-end engineering courses

Overview:

This is a guide that everyone can use to learn about the practice of front-end development. It broadly outlines and discusses the practice of front-end engineering: how to learn it and what tools are used when practicing it in 2019.

It is specifically written with the intention of being a professional resource for potential and currently practicing front-end developers to equip themselves with learning materials and development tools. Secondarily, it can be used by managers, CTOs, instructors, and head hunters to gain insights into the practice of front-end development.

The content of the handbook favors web technologies (HTML, CSS, DOM, and JavaScript) and those solutions that are directly built on top of these open technologies. The materials referenced and discussed in the book are either best in class or the current offering to a problem.

The book should not be considered a comprehensive outline of all resources available to a front-end developer. The value of the book is tied up in a terse, focused, and timely curation of just enough categorical information so as not to overwhelm anyone on any one particular subject matter.

The intention is to release an update to the content yearly. This is currently the fourth year an edition has been released.

What is in this Handbook:

Chapter 0 provides a lite recap of the year in front-end development and what may be to come. Chapter 1 & 2 aim to give a brief overview of the discipline and practice of front-end development. Chapters 3 & 4 organize and recommend learning paths and resources. Chapter 5 organizes and list the tools used by front-end developers and Chapter 6 highlights front-end information outlets.

Contribute content, suggestions, and fixes on github:

https://github.com/FrontendMasters/front-end-handbook-2019

Chapter 0. Recap of 2018 and Looking Forward

0.1 — Recap of Front-end Development in 2018

0.2 — In 2019, Expect...

Chapter 1. What Is a Front-end Developer?

This chapter provides a baseline explanation for front-end development and the front-end developer discipline.

Front-end web development, also known as client-side development is the practice of producing HTML, CSS and JavaScript for a website or Web Application so that a user can see and interact with them directly. The challenge associated with front end development is that the tools and techniques used to create the front end of a website change constantly and so the developer needs to constantly be aware of how the field is developing.> The objective of designing a site is to ensure that when the users open up the site they see the information in a format that is easy to read and relevant. This is further complicated by the fact that users now use a large variety of devices with varying screen sizes and resolutions thus forcing the designer to take into consideration these aspects when designing the site. They need to ensure that their site comes up correctly in different browsers (cross-browser), different operating systems (cross-platform) and different devices (cross-device), which requires careful planning on the side of the developer.> https://en.wikipedia.org/wiki/Front-end_web_development
Image source: https://www.upwork.com/hiring/development/front-end-developer/

A Front-end Developer...

A front-end developer architects and develops websites and web applications using web technologies (i.e., HTML, CSS, and JavaScript), which typically runs on the Open Web Platform or acts as compilation input for non-web platform environments (i.e., React Native).

A person enters into the field of front-end development by learning to build a website or web application which relies on HTML, CSS, and JavaScript and commonly runs in a web browser but can also run in a headless browser, WebView, or as compilation input for a native runtime environment. These four run times scenarios are explained below.

Web Browsers (most common)

A web browser is software used to retrieve, present, and traverse information on the WWW. Typically, browsers run on a desktop or laptop computer, tablet, or phone, but as of late a browser can be found on just about anything (i.e, on a fridge, in cars, etc.).

The most common web browsers are (shown in order of most used first):

Headless Browsers

Headless browsers are a web browser without a graphical user interface that can be controlled from a command line interface programmatically for the purpose of web page automation (e.g., functional testing, scraping, unit testing, etc.). Think of headless browsers as a browser that you can run programmatically from the command line that can retrieve and traverse web page code.

The most common headless browsers are:

Webviews

Webviews are used by a native OS, in a native application, to run web pages. Think of a webview like an iframe or a single tab from a web browser that is embedded in a native application running on a device (e.g., iOS, android, windows).

The most common solutions for webview development are:

  • Cordova (typically for native phone/tablet apps)
  • NW.js (typically used for desktop apps)
  • Electron (typically used for desktop apps)

Native from Web Tech

Eventually, what is learned from web browser development can be used by front-end developers to craft code for environments that are not fueled by a browser engine (i.e. web platform). As of late, development environments are being dreamed up that use web technologies (e.g., CSS and JavaScript), without web engines, to create native applications.

Some examples of these environments are:

Notes:

  1. Make sure you are clear what exactly is meant by the "web platform". Read the, ["Open Web Platform"](https://en.wikipedia.org/wiki/Open_Web_Platform ""Open Web Platform"") Wikipedia page. Explore the many technologies that make up the web platform.
Chapter 2. The Practice of Front-end Development: Overview

This chapter will break down and broadly describes the practice of front-end engineering starting with, "How Front-End Developers Are Made".

2.1 - How Front-End Developers Are Made

How exactly does one become a front-end developer? Well, it's complicated. Just consider this road map:

Image source: https://github.com/kamranahmedse/developer-roadmap

Today, in general, one can't go to college and expect to graduate with a degree in front-end engineering. And, I rarely hear of or meet front-end developers who suffered through what is likely a deprecated computer science degree or graphic design degree to end up writing HTML, CSS, and JavaScript professionally. From my perspective, most of the people working on the front-end today generally seem to be self-taught from the ground up or cross over into the front-end space from design or computer science fields.

If you were to set out today to become a front-end developer I would loosely strive to follow the process outlined below (Chapter 3 and Chapter 4 will dive into more details on learning resources).

  1. Learn, roughly, how the web platform works. Make sure you know the "what" and "where" of HTML, CSS, DOM, JavaScript, Domains, DNS, URLs, HTTP, browsers, and servers/hosting. Don't dive deep on anything just yet, just aim to understand the parts at play and how they loosely fit together. Start by building simple web pages.
  2. Learn HTML
  3. Learn CSS
  4. Learn JavaScript
  5. Learn DOM
  6. Learn the fundamentals of user interface design (i.e. UI patterns, interaction design, user experience design, and usability).
  7. Learn CLI/command line
  8. Learn the practice of software engineering (i.e., Application design/architecture, templates, Git, testing, monitoring, automating, code quality, development methodologies).
  9. Get opinionated and customize your tool box with whatever makes sense to your brain (e.g. Webpack, React, and Mobx).
  10. Learn Node.js

A short word of advice on learning. Learn the actual underlying technologies, before learning abstractions. Don't learn jQuery, learn the DOM. Don't learn SASS, learn CSS. Don't learn JSX, learn HTML. Don't learn TypeScript, learn JavaScript. Don't learn Handlebars, learn JavaScript ES6 templates. Don't just use Bootstrap, learn UI patterns.

Lately a lot of non-accredited, expensive, front-end code schools/bootcamps have emerged. These avenues of becoming a front-end developer are typically teacher directed courses, that follow a more traditional style of learning, from an official instructor (i.e., syllabus, test, quizzes, projects, team projects, grades, etc.).

Keep in mind, if you are considering an expensive training program, this is the web! Everything you need to learn is on the web for the taking, costing little to nothing. However, if you need someone to tell you how to take and learn what is low cost to free, and hold you accountable for learning it, you should consider a traditional instructor lead class room setting. Otherwise, I am not aware of any other profession that is practically free for the taking with an internet connection, a couple of dollars a month for screencasting memberships, and a burning desire for knowledge.

For example, if you want to get going today, consuming one or more of the following self-directed resources below can work:

When getting your start, you should fear most things that conceal complexity. Abstractions (e.g. jQuery) in the wrong hands can give the appearance of advanced skills, while all the time hiding the fact that a developer has an inferior understanding of the basics or underlying concepts.

It is assumed that on this journey you are not only learning, but also doing as you learn and investigate tools. Some suggest only doing to learn. While others suggest only learning about doing. I suggest you find a mix of both that matches how your brain works and do that. But, for sure, it is a mix! So, don't just read about it, do it. Learn, do. Learn, do. Repeat indefinitely because things change fast. This is why learning the fundamentals, and not abstractions, are so important.

2.2 - Front-End Job Titles

A great divide has been brewing in the front-end developer space for several years between two very different types of so-called front-end developers. On the one side, you have JavaScript-focused programmers who write JavaScript for front-end runtimes that likely have computer science skills with a software development history. They more than likely view HTML and CSS as an abstraction (i.e. JSX and CSS in JS). On the other side, you have, most likely, non-computer science educated developers who focus on HTML, CSS, and JavaScript as it specifically pertains to the UI. In 2019, when entering or trying to understand the front-end developer space you will absolutely feel this divide. The term front-end developer is on the verge of meaninglessness without clarifying words to address what type of front-end developer is being discussed.

Below is a list and description of various front-end job titles (Keep in mind titles are hard). The common, or most used (i.e., generic), title for a front-end developer is, "front-end developer" or "front-end engineer". Note that any job that contains the word "front-end", "client-side", "web UI", "HTML", "CSS", or "JavaScript" typically infers that a person has some degree of HTML, CSS, DOM, and JavaScript professional know how.

Front-End Developer: The generic job title that describes a developer who is skilled to some degree at HTML, CSS, DOM, and JavaScript and implementing these technologies on the web platform.

Front-End Engineer (aka JavaScript Developer or Full-stack JavaScript Developer): The job title given to a developer who comes from a computer science, engineering, background and is using these skills to work with front-end technologies. This role typically requires computer science knowledge and years of software development experience. When the word "JavaScript Application" is included in the job title, this will denote that the developer should be an advanced JavaScript developer possessing advanced programming, software development, and application development skills (i.e has years of experience building front-end software applications).

CSS/HTML Developer: The front-end job title that describes a developer who is skilled at HTML and CSS, excluding JavaScript and application, know how.

Front-End Web Designer: When the word "Designer" is included in the job title, this will denote that the designer will possess front-end skills (i.e., HTML & CSS) but also professional design (Visual Design and Interaction Design) skills.

UI (User Interface) Developer/Engineer: When the word "Interface" or "UI" is included in the job title, this will denote that the developer should posses interaction design skills in addition to front-end developer skills or front-end engineering skills.

Mobile/Tablet Front-End Developer: When the word "Mobile" or "Tablet" is included in the job title, this will denote that the developer has experience developing front-ends that run on mobile or tablet devices (either natively or on the web platform, i.e., in a browser).

Front-End SEO Expert: When the word "SEO" is included in the job title, this will denote that the developer has extensive experience crafting front-end technologies towards an SEO strategy.

Front-End Accessibility Expert: When the word "Accessibility" is included in the job title, this will denote that the developer has extensive experience crafting front-end technologies that support accessibility requirements and standards.

Front-End Dev. Ops: When the word "DevOps" is included in the job title, this will denote that the developer has extensive experience with software development practices pertaining to collaboration, integration, deployment, automation, and quality.

Front-End Testing/QA: When the word "Testing" or "QA" is included in the job title, this will denote that the developer has extensive experience testing and managing software that involves unit testing, functional testing, user testing, and A/B testing.

Notes:

  1. If you come across the "Full Stack" or the generic "Web Developer" terms in job titles these words may be used by an employer to describe a role that is responsible for all aspects of web/app development, i.e., both front-end (potentially including design) and back-end.

2.3 - Baseline Web Technologies Employed by Front-End Developers

The following core web technologies are employed by front-end developers (consider learning them in this order):

  1. Hyper Text Markup Language (aka HTML)
  2. Cascading Style Sheets (aka CSS)
  3. Uniform Resource Locators (aka URLs)
  4. Hypertext Transfer Protocol (aka HTTP)
  5. JavaScript Programming Language (aka ECMAScript 262)
  6. JavaScript Object Notation (aka JSON)
  7. Document Object Model (aka DOM)
  8. Web APIs (aka HTML5 and friends or Browser APIs)
  9. Web Content Accessibility Guidelines (aka WCAG) & Accessible Rich Internet Applications (aka ARIA)

For a comprehensive list of all web related specifications have a look at platform.html5.org or MDN Web APIs.

The nine technologies just mentioned are defined below along with a link to the relevant documentation and specification for each technology.

Hyper Text Markup Language (aka HTML)

HyperText Markup Language, commonly referred to as HTML, is the standard markup language used to create web pages. Web browsers can read HTML files and render them into visible or audible web pages. HTML describes the structure of a website semantically along with cues for presentation, making it a markup language, rather than a programming language.> — Wikipedia
Most relevant specifications / documentation:

Cascading Style Sheets (aka CSS)

Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. Although most often used to change the style of web pages and user interfaces written in HTML and XHTML, the language can be applied to any kind of XML document, including plain XML, SVG and XUL. Along with HTML and JavaScript, CSS is a cornerstone technology used by most websites to create visually engaging webpages, user interfaces for web applications, and user interfaces for many mobile applications.> — Wikipedia
Most relevant specifications / documentation:

Hypertext Transfer Protocol (aka HTTP)

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.> — Wikipedia
Most relevant specifications:

Uniform Resource Locators (aka URL)

A uniform resource locator (URL) (also called a web address) is a reference to a resource that specifies the location of the resource on a computer network and a mechanism for retrieving it. A URL is a specific type of uniform resource identifier (URI), although many people use the two terms interchangeably. A URL implies the means to access an indicated resource, which is not true of every URI. URLs occur most commonly to reference web pages (http), but are also used for file transfer (ftp), email (mailto), database access (JDBC), and many other applications.> — Wikipedia
Most relevant specifications:

Document Object Model (aka DOM)

The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents. The nodes of every document are organized in a tree structure, called the DOM tree. Objects in the DOM tree may be addressed and manipulated by using methods on the objects. The public interface of a DOM is specified in its application programming interface (API).> — Wikipedia
Most relevant specifications / documentation:

JavaScript Programming Language (aka ECMAScript 262)

JavaScript is a high level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification. Alongside HTML and CSS, it is one of the three essential technologies of World Wide Web content production; the majority of websites employ it and it is supported by all modern web browsers without plug-ins. JavaScript is prototype-based with first-class functions, making it a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. It has an API for working with text, arrays, dates and regular expressions, but does not include any I/O, such as networking, storage or graphics facilities, relying for these upon the host environment in which it is embedded.> — Wikipedia
Most relevant specifications / documentation:

Web APIs (aka HTML5 and friends)

When writing code for the Web using JavaScript, there are a great many APIs available. Below is a list of all the interfaces (that is, types of objects) that you may be able to use while developing your Web app or site.> — Mozilla
Most relevant documentation:

JavaScript Object Notation (aka JSON)

It is the primary data format used for asynchronous browser/server communication (AJAJ), largely replacing XML (used by AJAX). Although originally derived from the JavaScript scripting language, JSON is a language-independent data format. Code for parsing and generating JSON data is readily available in many programming languages. The JSON format was originally specified by Douglas Crockford. It is currently described by two competing standards, RFC 7159 and ECMA-404. The ECMA standard is minimal, describing only the allowed grammar syntax, whereas the RFC also provides some semantic and security considerations. The official Internet media type for JSON is application/json. The JSON filename extension is .json.> — Wikipedia
Most relevant specifications:

Web Content Accessibility Guidelines (aka WCAG) & Accessible Rich Internet Applications (aka ARIA)

Accessibility refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e., unassisted) and "indirect access" meaning compatibility with a person's assistive technology (for example, computer screen readers).> — Wikipedia* Web Accessibility Initiative (WAI)

2.4 - Potential Front-end Developer Skills

Image source: http://blog.naustud.io/2015/06/baseline-for-modern-front-end-developers.html

A basic to advanced understanding of HTML, CSS, DOM, JavaScript, HTTP/URL, and web browsers is assumed for any type of professional front-end developer role.

Beyond the skills just mentioned, a front-end developer might also be specifically skilled in one or more of the following:

  • Content Management Systems (aka CMS)
  • Node.js
  • Cross-Browser Testing
  • Cross-Platform Testing
  • Unit Testing
  • Cross-Device Testing
  • Accessibility / WAI-ARIA
  • Search Engine Optimization (aka SEO)
  • Interaction or User Interface Design
  • User Experience
  • Usability
  • E-commerce Systems
  • Portal Systems
  • Wireframing
  • CSS Layout / Grids
  • DOM Manipulation (e.g., jQuery)
  • Mobile Web Performance
  • Load Testing
  • Performance Testing
  • Progressive Enhancement / Graceful Degradation
  • Version Control (e.g., GIT)
  • MVC / MVVM / MV*
  • Functional Programming
  • Data Formats (e.g., JSON, XML)
  • Data APIs (e.g Restful API)
  • Web Font Embedding
  • Scalable Vector Graphics (aka SVG)
  • Regular Expressions
  • Microdata / Microformats
  • Task Runners, Build Tools, Process Automation Tools
  • Responsive Web Design
  • Object-Oriented Programming
  • Application Architecture
  • Modules
  • Dependency Managers
  • Package Managers
  • JavaScript Animation
  • CSS Animation
  • Charts / Graphs
  • UI Widgets
  • Code Quality Testing
  • Code Coverage Testing
  • Code Complexity Analysis
  • Integration Testing
  • Command Line / CLI
  • Templating Strategies
  • Templating Engines
  • Single Page Applications
  • Web/Browser Security
  • Browser Developer Tools

2.5 - Front-End Developers Develop For...

A front-end developer crafts HTML, CSS, and JS that typically runs on the web platform (e.g. a web browser) delivered from one of the following operating systems (aka OSs):

These operating systems typically run on one or more of the following devices:

  • Desktop computer
  • Laptop / netbook computer
  • Mobile phone
  • Tablet
  • TV
  • Watch
  • Things (i.e., anything you can imagine, car, refrigerator, lights, thermostat, etc.)

Image source: https://www.enterpriseirregulars.com/104084/roundup-internet-things-forecasts-market-estimates-2015/

Generally speaking, front-end technologies can run on the aforementioned operating systems and devices using the following run time web platform scenarios:

2.6 - Front-End on a Team

A front-end developer is typically only one player on a team that designs and develops web sites, web applications, or native applications running from web technologies.

A bare-bones development team for building professional web sites or software for the web platform will typically, minimally, contain the following roles.

  • Visual Designer (i.e., fonts, colors, spacing, emotion, visuals concepts & themes)
  • UI/Interaction Designer/Information Architect (i.e., wireframes, specifying all user interactions and UI functionality, structuring information)
  • Front-End Developer (i.e., writes code that runs in client/on the device)
  • Back-End Developer (i.e., writes code that runs on the server)

The roles are ordered according to overlapping skills. A front-end developer will typically have a good handle on UI/Interaction design as well as back-end development. It is not uncommon for team members to fill more than one role by taking on the responsibilities of an over-lapping role.

It is assumed that the team mentioned above is being directed by a project lead or some kind of product owner (i.e., stakeholder, project manager, project lead, etc.)

A larger web team might include the following roles not shown above:

  • SEO Strategists
  • DevOps Engineers
  • Performance Engineers
  • API Developers
  • Database Administrators
  • QA Engineers / Testers

2.7 - Generalist/Full-Stack Myth

The term "Full-Stack" developer has come to take on several meanings. So many, that not one meaning is clear when the term is used. Just consider the results from the two surveys shown below. These results might lead one to believe that being a full-stack developer is commonplace. But, in my almost 20 years of experience, this is anything but the case in a professional context.

Image source: https://medium.freecodecamp.com/we-asked-15-000-people-who-they-are-and-how-theyre-learning-to-code-4104e29b2781#.ngcpn8nlz

Image source: https://insights.stackoverflow.com/survey/2017#developer-profile-specific-developer-types

The roles to design and develop a website or web application require a deep set of skills and vast experience in the area of visual design, UI/interaction design, front-end development, and back-end development. Any person who can fill one or more of these 4 roles at a professional level is an extremely rare commodity.

Pragmatically, you should seek to be, or seek to hire, an expert in one of these roles (i.e. Visual Design, Interaction Design/IA, Front-end Dev, Back-end Dev). Those who claim to operate at an expert level at one or more of these roles are exceptionally rare.

However, given that JavaScript has infiltrated all layers of a technology stack (i.e. Node.js) finding a full-stack JS developer who can code the front-end and back-end is becoming less mythical. Typically, these full-stack developers only deal with JavaScript. A developer who can code the front-end, back-end, API, and database isn't as absurd as it once was (excluding visual design, interaction design, and CSS). Still mythical in my opinion, but not as uncommon as it once was. Thus, I wouldn't recommend a developer set out to become a "full-stack" developer. In rare situations, it can work. But, as a general concept for building a career as a front-end developer, I'd focus on front-end technologies.

2.8 - Front-End Interviews

Preparing:

Quiz's:

Questions you may get asked:

Questions you ask:

2.9 - Front-End Job Boards

A plethora of technical job listing outlets exist. The narrowed list below are currently the most relevant resources for finding a specific front-end position/career.

Notes:

  1. Want to work remotely as a front-end developer checkout these remote-friendly companies.

2.10 - Front-End Salaries

The national average in the U.S for a mid-level front-end developer is somewhere between $65k and 100k.

Of course when you first start expect to enter the field at around 40k depending upon location and experience.

Notes:

  1. A lead/senior front-end developer/engineer can potentially live wherever they want (i.e., work remotely) and make over A lead/senior front-end developer/engineer can potentially live wherever they want (i.e., work remotely) and make over $150k a year (visit angel.co, sign-up, review front-end jobs over $150k or examine the salary ranges on Stack Overflow Jobs).50k a year (visit angel.co, sign-up, review front-end jobs over A lead/senior front-end developer/engineer can potentially live wherever they want (i.e., work remotely) and make over $150k a year (visit angel.co, sign-up, review front-end jobs over $150k or examine the salary ranges on Stack Overflow Jobs).50k or examine the salary ranges on Stack Overflow Jobs).
Chapter 3. Learning Front-end Dev: Self Directed Resources/Recommendations

This chapter highlights the many resources (video training, books, etc.) that an individual can use to direct their own learning process and career as a front-end developer.

The learning resources identified (articles, books, videos, screencasts etc..) will include both free and paid material. Paid material will be indicated with [$].

3.1. - Learn Internet/Web

The Internet is a global system of interconnected computer networks that use the Internet protocol suite (TCP/IP) to link several billion devices worldwide. It is a network of networks that consists of millions of private, public, academic, business, and government networks of local to global scope, linked by a broad array of electronic, wireless, and optical networking technologies. The Internet carries an extensive range of information resources and services, such as the inter-linked hypertext documents and applications of the World Wide Web (WWW), electronic mail, telephony, and peer-to-peer networks for file sharing.> — Wikipedia

Image source: https://www.helloitsliam.com/2014/12/20/how-the-internet-works-infographic/

Image source: http://www.bitrebels.com/technology/find-out-who-runs-the-internet-chart/

3.2. - Learn Web Browsers

A web browser (commonly referred to as a browser) is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier (URI/URL) and may be a web page, image, video or other piece of content. Hyperlinks present in resources enable users easily to navigate their browsers to related resources. Although browsers are primarily intended to use the World Wide Web, they can also be used to access information provided by web servers in private networks or files in file systems.> — Wikipedia#### The most commonly used browsers (on desktop and mobile) are:

  1. Chrome (engine: Blink + V8)
  2. Firefox (engine: Gecko + SpiderMonkey)
  3. Internet Explorer (engine: Trident + Chakra)
  4. Safari (engine: Webkit + SquirrelFish)

Image source: http://gs.statcounter.com/browser-market-share

Evolution of Browsers & Web Technologies (i.e., APIs)

The Most Commonly Used Headless Browser Are:

How Browsers Work

Optimizing for Browsers:

Comparing Browsers

Browser Hacks

Developing for Browsers

In the past, front-end developers spent a lot of time making code work in several different browsers. This was once a bigger issue than it is today. Today, abstractions (e.g., React, Webpack, Post-CSS, Babel etc...) combined with modern browsers make browser development fairly easy. The new challenge is not which browser the user will use, but on which device they will run the browser.

Evergreen Browsers

The latest versions of most modern browsers are considered evergreen browsers. That is, in theory, they are supposed to automatically update themselves silently without prompting the user. This move towards self-updating browsers has been in reaction to the slow process of eliminating older browsers that do not auto-update.

Picking a Browser

As of today, most front-end developers use Chrome and "Chrome Dev Tools" to develop front-end code. However, the most used modern browsers all offer a flavor of developer tools. Picking one to use for development is a subjective choice. The more important issue is knowing which browsers, on which devices, you have to support and then testing appropriately.

3.3 - Learn Domain Name System (aka DNS)

The Domain Name System (DNS) is a hierarchical distributed naming system for computers, services, or any resource connected to the Internet or a private network. It associates various information with domain names assigned to each of the participating entities. Most prominently, it translates domain names, which can be easily memorized by humans, to the numerical IP addresses needed for the purpose of computer services and devices worldwide. The Domain Name System is an essential component of the functionality of most Internet services because it is the Internet's primary directory service.> — Wikipedia

Image source: http://www.digital-digest.com/blog/DVDGuy/wp-content/uploads/2011/11/how_dns_works.jpg

3.4 - Learn HTTP/Networks (Including CORS & WebSockets)

HTTP - The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.> — Wikipedia#### HTTP Specifications

HTTP Docs

HTTP Videos/Articles/Tutorials

HTTP Status Codes

CORS - Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g., fonts) on a web page to be requested from another domain outside the domain from which the resource originated.> — Wikipedia#### CORS Specifications

CORS

WebSockets - WebSocket is a protocol providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.> — Wikipedia#### WebSockets

3.5 - Learn Web Hosting

A web hosting service is a type of Internet hosting service that allows individuals and organizations to make their website accessible via the World Wide Web. Web hosts are companies that provide space on a server owned or leased for use by clients, as well as providing Internet connectivity, typically in a data center.> — Wikipedia#### General Learning:

Image source: https://firstsiteguide.com/wp-content/uploads/2016/06/what-is-web-hosting-infographic.jpg

3.6 - Learn General Front-End Development

3.7 - Learn User Interface/Interaction Design

User Interface Design - User interface design (UI) or user interface engineering is the design of user interfaces for machines and software, such as computers, home appliances, mobile devices, and other electronic devices, with the focus on maximizing the user experience. The goal of user interface design is to make the user's interaction as simple and efficient as possible, in terms of accomplishing user goals (user-centered design).> — Wikipedia> Interaction Design Pattern - A design pattern is a formal way of documenting a solution to a common design problem. The idea was introduced by the architect Christopher Alexander for use in urban planning and building architecture, and has been adapted for various other disciplines, including teaching and pedagogy, development organization and process, and software architecture and design.> — Wikipedia> User Experience Design - User Experience Design (UXD or UED or XD) is the process of enhancing user satisfaction by improving the usability, accessibility, and pleasure provided in the interaction between the user and the product. User experience design encompasses traditional human–computer interaction (HCI) design, and extends it by addressing all aspects of a product or service as perceived by users.> — Wikipedia> Human–Computer Interaction - Human–computer interaction (HCI) researches the design and use of computer technology, focusing particularly on the interfaces between people (users) and computers. Researchers in the field of HCI both observe the ways in which humans interact with computers and design technologies that lets humans interact with computers in novel ways.> — Wikipedia
Minimally I'd suggest reading the following canonical texts on the matter so one can support and potential build usable user interfaces.

3.8 - Learn HTML & CSS

HTML - HyperText Markup Language, commonly referred to as HTML, is the standard markup language used to create web pages. Web browsers can read HTML files and render them into visible or audible web pages. HTML describes the structure of a website semantically along with cues for presentation, making it a markup language, rather than a programming language.> — Wikipedia> CSS - Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. Although most often used to change the style of web pages and user interfaces written in HTML and XHTML, the language can be applied to any kind of XML document, including plain XML, SVG and XUL. Along with HTML and JavaScript, CSS is a cornerstone technology used by most websites to create visually engaging webpages, user interfaces for web applications, and user interfaces for many mobile applications.> — Wikipedia
Liken to constructing a house, one might consider HTML the framing and CSS to be the painting & decorating.

General Learning:

Mastering CSS:

References/Docs:

Glossary/Vocabulary:

Standards/Specifications:

Architecting CSS:

Authoring/Architecting Conventions:

3.9 - Learn Search Engine Optimization

Search engine optimization (SEO) is the process of affecting the visibility of a website or a web page in a search engine's unpaid results — often referred to as "natural," "organic," or "earned" results. In general, the earlier (or higher ranked on the search results page), and more frequently a site appears in the search results list, the more visitors it will receive from the search engine's users. SEO may target different kinds of search, including image search, local search, video search, academic search, news search and industry-specific vertical search engines.> — Wikipedia

Image source: https://visual.ly/community/infographic/computers/how-does-seo-work

General Learning:

3.10 - Learn JavaScript

JavaScript is a high level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification. Alongside HTML and CSS, it is one of the three essential technologies of World Wide Web content production; the majority of websites employ it and it is supported by all modern web browsers without plug-ins. JavaScript is prototype-based with first-class functions, making it a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. It has an API for working with text, arrays, dates and regular expressions, but does not include any I/O, such as networking, storage or graphics facilities, relying for these upon the host environment in which it is embedded.> — Wikipedia#### Getting Started:

General Learning:

Mastering:

Functional JavaScript:

References/Docs:

Glossary/Encyclopedia/Jargon:

Standards/Specifications:

Style:

Deprecated JS Learning Resources:

JS Explorers/Visualizers:

3.11 - Learn DOM, BOM, CSSOM & jQuery

DOM - The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents. The nodes of every document are organized in a tree structure, called the DOM tree. Objects in the DOM tree may be addressed and manipulated by using methods on the objects. The public interface of a DOM is specified in its application programming interface (API).> — Wikipedia> BOM - The Browser Object Model (BOM) is a browser-specific convention referring to all the objects exposed by the web browser. Unlike the Document Object Model, there is no standard for implementation and no strict definition, so browser vendors are free to implement the BOM in any way they wish.> — Wikipedia> jQuery - jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. jQuery is the most popular JavaScript library in use today, with installation on 65% of the top 10 million highest-trafficked sites on the Web. jQuery is free, open-source software licensed under the MIT License.> — Wikipedia
The ideal path, but certainly the most difficult, would be to first learn JavaScript, then the DOM, then jQuery. However, do what makes sense to your brain. Most front-end developers learn about JavaScript and then DOM by way of first learning jQuery. Whatever path you take, just make sure JavaScript, the DOM, and jQuery don't become a black box.

General Learning:

Mastering:

References/Docs:

Standards/Specifications:

3.12 - Learn Web Animation

General Learning:

Standards/Specifications:

3.13 - Learn Web Fonts, Icons, & Images

Web typography refers to the use of fonts on the World Wide Web. When HTML was first created, font faces and styles were controlled exclusively by the settings of each Web browser. There was no mechanism for individual Web pages to control font display until Netscape introduced the <font> tag in 1995, which was then standardized in the HTML 3.2 specification. However, the font specified by the tag had to be installed on the user's computer or a fallback font, such as a browser's default sans-serif or monospace font, would be used. The first Cascading Style Sheets specification was published in 1996 and provided the same capabilities.> The CSS2 specification was released in 1998 and attempted to improve the font selection process by adding font matching, synthesis and download. These techniques did not gain much use, and were removed in the CSS2.1 specification. However, Internet Explorer added support for the font downloading feature in version 4.0, released in 1997. Font downloading was later included in the CSS3 fonts module, and has since been implemented in Safari 3.1, Opera 10 and Mozilla Firefox 3.5. This has subsequently increased interest in Web typography, as well as the usage of font downloading.> — Wikipedia#### Fonts:

Icons:

Images:

3.14 - Learn Accessibility

Accessibility refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e., unassisted) and "indirect access" meaning compatibility with a person's assistive technology (for example, computer screen readers).> Accessibility can be viewed as the "ability to access" and benefit from some system or entity. The concept focuses on enabling access for people with disabilities, or special needs, or enabling access through the use of assistive technology; however, research and development in accessibility brings benefits to everyone.> Accessibility is not to be confused with usability, which is the extent to which a product (such as a device, service, or environment) can be used by specified users to achieve specified goals with effectiveness, efficiency and satisfaction in a specified context of use.> Accessibility is strongly related to universal design which is the process of creating products that are usable by people with the widest possible range of abilities, operating within the widest possible range of situations. This is about making things accessible to all people (whether they have a disability or not).> — Wikipedia#### General Learning:

Standards/Specifications:

3.15 - Learn Web/Browser APIs

Image source: http://www.evolutionoftheweb.com/

The BOM (Browser Object Model) and the DOM (Document Object Model) are not the only browser APIs that are made available on the web platform inside of browsers. Everything that is not specifically the DOM or BOM, but an interface for programming the browser could be considered a web or browser API (tragically in the past some of these APIs have been called HTML5 APIs which confuses their own specifics/standardize with the actual HTML5 specification specifying the HTML5 markup language). Note that web or browser APIs do include device APIs (e.g., <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getBattery" target="_blank">Navigator.getBattery()</a>) that are available through the browser on tablet and phones devices.

You should be aware of and learn, where appropriate, web/browser APIs. A good tool to use to familiarize oneself with all of these APIs would be to investigate the HTML5test.com results for the 5 most current browsers.

MDN has a great deal of information about web/browser APIs.

Keep in mind that not every API is specified by the W3C or WHATWG.

In addition to MDN, you might find the following resources helpful for learning about all the web/browser API's:

3.16 - Learn JSON (JavaScript Object Notation)

JSON, (canonically pronounced sometimes JavaScript Object Notation), is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is the primary data format used for asynchronous browser/server communication (AJAJ), largely replacing XML (used by AJAX).> Although originally derived from the JavaScript scripting language, JSON is a language-independent data format. Code for parsing and generating JSON data is readily available in many programming languages.> The JSON format was originally specified by Douglas Crockford. It is currently described by two competing standards, RFC 7159 and ECMA-404. The ECMA standard is minimal, describing only the allowed grammar syntax, whereas the RFC also provides some semantic and security considerations. The official Internet media type for JSON is application/json. The JSON filename extension is .json.> — Wikipedia#### General Learning:

References/Docs:

Standards/Specifications:

Architecting:

3.17 - Learn JS Templates

A JavaScript template is typically used, but not always with a MV* solution to separate parts of the view (i.e., the UI) from the logic and model (i.e., the data or JSON).

Note that JavaScript 2015 (aka ES6) added a native templating mechanism called ["Templates strings"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings ""Templates strings""). Additionally, templating as of late has been replaced by things like JSX, a template element, or HTML strings.

If I was not using React & JSX I'd first reach for JavaScript ["Templates strings"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings ""Templates strings"") and when that was lacking move to nunjucks.

3.18 - Learn Static Site Generators

Static site generators, typically written using server side code (i.e., ruby, php, python, nodeJS, etc.), produce static HTML files from static text/data + templates that are intended to be sent from a server to the client statically without a dynamic nature.

General Learning:

3.19 - Learn Computer Science via JS

3.20 - Learn Front-End Application Architecture

General Learning:

Deprecated Learning Materials:

Not a lot of general content is being created on this topic as of late. Most of the content offered for learning how to build front-end/SPA/JavaScript applications presupposes you've decided up a tool like Angular, Ember, React, or Aurelia.

My advice, in 2019 learn React and Mobx and Apollo/graphql.

3.21 - Learn Data (i.e. JSON) API Design

3.22 - Learn React

Learning React:

Mastering React:

Once you have a good handle on React move on to learning a more robust state management solution like MobX. If you are an experienced developer with Functional Programming knowledge look at Redux. If you need help understanding the role of state management beyond React's setState watch, "Advanced State Management in React (feat. Redux and MobX)".

3.23 - Learn Application State Management

3.24 - Learn Progressive Web App

Unlike traditional applications, progressive web apps are a hybrid of regular web pages (or websites) and a mobile application. This new application model attempts to combine features offered by most modern browsers with the benefits of mobile experience.> In 2015, designer Frances Berriman and Google Chrome engineer Alex Russell coined the term "Progressive Web Apps" to describe apps taking advantage of new features supported by modern browsers, including Service Workers and Web App Manifests, that let users upgrade web apps to be first-class applications in their native OS.> According to Google Developers, these characteristics are:* Progressive - Work for every user, regardless of browser choice because they’re built with progressive enhancement as a core tenet.

  • Responsive - Fit any form factor: desktop, mobile, tablet, or forms yet to emerge.
  • Connectivity independent - Service workers allow work offline, or on low quality networks.
  • App-like - Feel like an app to the user with app-style interactions and navigation.
  • Fresh - Always up-to-date thanks to the service worker update process.
  • Safe - Served via HTTPS to prevent snooping and ensure content hasn’t been tampered with.
  • Discoverable - Are identifiable as “applications” thanks to W3C manifests[6] and service worker registration scope allowing search engines to find them.
  • Re-engageable - Make re-engagement easy through features like push notifications.
  • Installable - Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.
  • Linkable - Easily shared via a URL and do not require complex installation.

Wikipedia* A Beginner’s Guide To Progressive Web Apps [read]

3.25 - Learn JS API Design

3.26 - Learn Browser Web Developer Tools

Web development tools allow web developers to test and debug their code. They are different from website builders and IDEs in that they do not assist in the direct creation of a webpage, rather they are tools used for testing the user facing interface of a website or web application.> Web development tools come as browser add-ons or built in features in web browsers. The most popular web browsers today like, Google Chrome, Firefox, Opera, Internet Explorer, and Safari have built in tools to help web developers, and many additional add-ons can be found in their respective plugin download centers.> Web development tools allow developers to work with a variety of web technologies, including HTML, CSS, the DOM, JavaScript, and other components that are handled by the web browser. Due to the increasing demand from web browsers to do more popular web browsers have included more features geared for developers.> — Wikipedia
While most browsers come equipped with web developer tools, the Chrome developer tools are currently the most talked about and widely used.

I'd suggest learning and using the Chrome web developer tools, simply because the best resources for learning web developer tools revolves around Chrome DevTools.

Learn Chrome Web Developer Tools:

Chrome Web Developer Tools Docs:

3.27 - Learn the Command Line (aka CLI)

A command-line interface or command language interpreter (CLI), also known as command-line user interface, console user interface, and character user interface (CUI), is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines).> — Wikipedia#### General Learning:

Mastering:

3.28 - Learn Node.js

Node.js is an open-source, cross-platform runtime environment for developing server-side web applications. Node.js applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux, FreeBSD, NonStop, IBM AIX, IBM System z and IBM i. Its work is hosted and supported by the Node.js Foundation, a collaborative project at Linux Foundation.> Node.js provides an event-driven architecture and a non-blocking I/O API designed to optimize an application's throughput and scalability for real-time web applications. It uses Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a web server without software such as Apache HTTP Server, Nginx or IIS.> — Wikipedia#### General Learning:

3.29 - Learn Modules

General Learning:

References/Docs:

3.30 - Learn Module loaders/bundlers

Webpack:

Rollup:

3.31 - Learn Package Manager

A package manager or package management system is a collection of software tools that automates the process of installing, upgrading, configuring, and removing software packages for a computer's operating system in a consistent manner. It typically maintains a database of software dependencies and version information to prevent software mismatches and missing prerequisites.> — Wikipedia#### General Learning:

3.32 - Learn Version Control

A component of software configuration management, version control, also known as revision control or source control, is the management of changes to documents, computer programs, large web sites, and other collections of information. Changes are usually identified by a number or letter code, termed the "revision number," "revision level," or simply "revision." For example, an initial set of files is "revision 1." When the first change is made, the resulting set is "revision 2," and so on. Each revision is associated with a timestamp and the person making the change. Revisions can be compared, restored, and with some types of files, merged.> — Wikipedia
The most common solution used for version control today is Git. Learn it!

General Learning:

Mastering:

References/Docs:

3.33 - Learn Build and Task Automation

Build automation is the process of automating the creation of a software build and the associated processes including: compiling computer source code into binary code, packaging binary code, and running automated tests.> — Wikipedia#### General Learning:

References/Docs:

Gulp is great. However, you might only need npm run. Before turning to additional complexity in your application stack ask yourself if npm run can do the job. If you need more, use Gulp.

Read:

3.34 - Learn Site Performance Optimization

Web performance optimization, WPO, or website optimization is the field of knowledge about increasing the speed in which web pages are downloaded and displayed on the user's web browser. With the average internet speed increasing globally, it is fitting for website administrators and webmasters to consider the time it takes for websites to render for the visitor.> — Wikipedia#### General Learning:

3.35 - Learn Testing

Unit Testing - In computer programming, unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use. Intuitively, one can view a unit as the smallest testable part of an application.> — Wikipedia> Functional Testing - Functional testing is a quality assurance (QA) process and a type of black box testing that bases its test cases on the specifications of the software component under test. Functions are tested by feeding them input and examining the output, and internal program structure is rarely considered (not like in white-box testing). Functional testing usually describes what the system does.> — Wikipedia> Integration Testing - Integration testing (sometimes called integration and testing, abbreviated I&T) is the phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the integrated system ready for system testing.> — Wikipedia#### General Learning:

3.36 - Learn Headless Browsers

A headless browser is a web browser without a graphical user interface.> Headless browsers provide automated control of a web page in an environment similar to popular web browsers, but are executed via a command line interface or using network communication. They are particularly useful for testing web pages as they are able to render and understand HTML the same way a browser would, including styling elements such as page layout, color, font selection and execution of JavaScript and AJAX which are usually not available when using other testing methods. Google stated in 2009 that using a headless browser could help their search engine index content from websites that use AJAX.> — Wikipedia* Getting Started with Headless Chrome [readme]

PhantomJS is no longer maintained, Headless Chrome steps in.

3.37 - Learn Offline Development

Offline development (aka offline first) is an area of knowledge and discussion around development practices for devices that are not always connected to the Internet or a power source.

General Learning:

3.38 - Learn Web/Browser/App Security

3.39 - Learn Multi-Device Development

Image source: http://bradfrost.com/blog/post/this-is-the-web/

A website or web application can run on a wide range of computers, laptops, tablets and phones, as well as a handful of new devices (watches, thermostats, fridges, etc.). How you determine what devices you'll support and how you will develop to support those devices is called, "multi-device development strategy". Below, I list the most common multi-device development strategies.

  • Build a responsive (RWD) web site/app for all devices.
  • Build an adaptive/progressively enhanced web site/app for all devices.
  • Build a website, web app, native app, or hybrid-native app for each individual device or a grouping of devices.
  • Attempt to retrofit something you have already built using bits and parts from strategies 1, 2 or 3.

General Learning:

Chapter 4. Learning Front-end Dev: Instructor Directed Resources/Recommendations

This chapter highlights a few options for instructor directed learning via front-end development schools, courses, programs, and bootcamps.

The table below contains a small selection of instructor-led courses (i.e. programs, schools, and bootcamps). Use the table to get a general idea of what is available, the cost, duration, and locations of courses. (Be aware the information can change quickly)

company program price estimate on site remote duration Betamore Front-end Web Development 3,000 Baltimore, MD 10 weeks BLOC Become a Front-end Developer 4,999 yes 16 weeks @ 25hr/wk or 32 weeks @ 10hr/wk General Assembly Front-end Web Development 3,500 multiple locations 3 hrs/day 2 days/wk for 8 weeks Thinkful Front-end Web Development 300 per month yes 15 hrs/wk for 3 months Turing School of Software & Design Front-End Engineering 20,000 Denver, CO 7 months full time Notes:

  1. For a complete list of schools, courses, programs, and bootcamps to evaluate have a look at switchup.org or coursereport.com.

If you can't afford a directed education (can be very expensive), a self directed education using screencasts, books, and articles is a viable alternative to learn front-end development for the self-driven individual.

Chapter 5. Front-end Dev Tools

This chapter identifies the tools of the trade. Make sure you understanding the category that a set of tools falls within, before studying the tools themselves. Note that just because a tool is listed, or a category of tools is documented, this does not equate to an assertion on my part that a front-end developer should learn it and use it. Choose your own toolbox. I'm just providing the common toolbox options.

5.1 - Doc/API Browsing Tools

Tools to browse common developer documents and developer API references.

Cheatsheets:

5.2 - SEO Tools

General SEO Tools:

Tools for Finding SEO Tools:

5.3 - Prototyping & Wireframing Tools

Creating:

Collaboration / Presenting:

5.4 - Diagramming Tools

5.5 - HTTP/Network Tools

5.6 - Code Editing Tools

A source code editor is a text editor program designed specifically for editing source code of computer programs by programmers. It may be a standalone application or it may be built into an integrated development environment (IDE) or web browser. Source code editors are the most fundamental programming tool, as the fundamental job of programmers is to write and edit source code.> — Wikipedia
Front-end code can minimally be edited with a simple text editing application like Notepad or TextEdit. But, most front-end practitioners use a code editor specifically design for editing a programming language.

Code editors come in all sorts of types and size, so to speak. Selecting one is a rather subjective engagement. Choose one, learn it inside and out, then get on to learning HTML, CSS, DOM, and JavaScript.

However, I do strongly believe, minimally, a code editor should have the following qualities (by default or by way of plugins):

  1. Good documentation on how to use the editor
  2. Report (i.e., hinting/linting/errors) on the code quality of HTML, CSS, and JavaScript.
  3. Offer syntax highlighting for HTML, CSS, and JavaScript.
  4. Offer code completion for HTML, CSS, and JavaScript.
  5. Be customizable by way of a plug-in architecture
  6. Have available a large repository of third-party/community plug-ins that can be used to customize the editor to your liking
  7. Be small, simple, and not coupled to the code (i.e., not required to edit the code)

Code Editors:

Online Code Editors:

Shareable & Runnable Simple Code Editors:

Used to share limited amounts of immediately runnable code. Not a true code editor but a tool that can be used to share small amounts of immediately runnable code in a web browser.

I recommending using Visual Studio Code because of the quality of the tool and the continuous improvements made to the editor that likely won't stop or slow due to the fact that Microsoft is behind the tool. It is widely used:

Image source: https://2018.stateofjs.com/other-tools/text_editors

5.7 - Browser Tools

JS Utilities to fix Browsers:

General Reference Tools to Determine If X Browser Supports X:

Browser Development/Debug Tools:

Chrome Developer Tools (aka DevTools)Per-Panel DocumentationCommand Line API ReferenceKeyboard & UI Shortcuts ReferenceSettings* Firefox Developer Tools

JavaScript Utilities to Determine If X Browser Supports X:

Broad Browser Polyfills/Shims:

Hosted Testing/Automation for Browsers:

Headless Browsers:

Browser Automation:

Used for functional testing and monkey testing.

Browser Hacks:

Browser Syncing Tools:

Browser List:

Share target browsers between different front-end tools, like Autoprefixer, Stylelint and babel-preset-env.
Browserslisthttp://browserl.ist/### 5.8 - HTML Tools

HTML Templates/Boilerplates/Starter Kits:

HTML Polyfill:

Transpiling:

References:

Linting/Hinting:

Optimizer:

Online Creation/Generation/Experimentation Tools:

Authoring Conventions:

Workflow:

HTML Outliner:

Trending HTML Repositories on GitHub This Month:

https://github.com/trending?l=html&since=monthly

5.9 - CSS Tools

CSS Utilities:

CSS Frameworks (utilities + UI):

Mobile Only CSS Frameworks:

CSS Reset:

A CSS Reset (or “Reset CSS”) is a short, often compressed (minified) set of CSS rules that resets the styling of all HTML elements to a consistent baseline.> — cssreset.com* Eric Meyer's “Reset CSS” 2.0

Transpiling:

References:

Linting/Hinting:

Code Formatter/Beautifier:

Optimizer:

Online Creation/Generation/Experimentation Tools:

Architecting CSS:

Authoring/Architecting Conventions:

Style Guide Resources:

CSS in JS:

Trending CSS Repositories on GitHub This Month:

https://github.com/trending?l=css&since=monthly

5.10 - DOM Tools

DOM Libraries/Frameworks:

DOM Utilities:

DOM Event Tools:

DOM Performance Tools:

References:

DOM Polyfills/Shims:

Virtual DOM:

5.11 - JavaScript Tools

JS Utilities:

Transforming JavaScript Objects Tool:

Transpiling / Type Checking (ES to ES):

Type Checking (ES to ES):

Transpiling (ES to ES):

Code-analysis Engine:

Linting/Hinting & Style Linter:

Unit Testing:

Testing Assertions for Unit Testing:

Test Spies, Stubs, and Mocks for Unit Testing:

Code Formater/Beautifier:

Performance Testing:

Visualization, Static Analysis, Complexity, Coverage Tools:

Optimizer:

Obfuscate:

Sharable/Runnable Code Editors:

Online Regular Expression Editors/Visual Tools:

Authoring Convention Tools:

Trending JS Repositories on GitHub This Month:

https://github.com/trending?l=javascript&since=monthly

Most Depended upon Packages on NPM:

https://www.npmjs.com/browse/depended

5.12 - Headless CMS Tools

Site Generator Listings:

5.13 - Static Site Generators Tools

Site Generator Listings:

5.14 - Accessibility Tools

Guides

Site Scanners

Color Contrast Testers

Low-Vision Simulators

Screen Readers

Readability Testers

Articles

5.15 - App Frameworks (Desktop, Mobile, Tablet, etc.) Tools

Front-End App Frameworks:

Native Hybrid Mobile WebView (i.e., Browser Engine Driven) Frameworks:

These solutions typically use Cordova, crosswalk, or a custom WebView as a bridge to native APIs.

Native Hybrid Mobile Development Webview (i.e., Browser Engine Driven) Environments/Platforms/Tools:

These solutions typically use Cordova, crosswalk, or a custom WebView as a bridge to native APIs.

Native Desktop App Frameworks:

Native Mobile App Frameworks (Aka JavaScript Native Apps)

These solutions use a JS engine at runtime to interpret JS and bridge that to native APIs. No browser engine or WebView is used. The UI is constructed from native UI components.

References & demo apps:

Performance:

If you are new to front-end/JavaScript application development I'd start with Vue.js. Then I'd work my way to React. Then I'd look at Angular 2+, Ember, or Aurelia.

If you are building a simple website that has minimal interactions with data (i.e. mostly a static content web site), you should avoid a front-end framework. A lot of work can be done with a task runner like Gulp and jQuery, while avoiding the unnecessary complexity of learning and using an app framework tool.

Want something smaller than React, consider Preact. Preact is an attempt to recreate the core value proposition of React (or similar libraries like Mithril) using as little code as possible, with first-class support for ES2015. Currently the library is around 3kb (minified & gzipped).

5.16 - JavaScript App Manager

5.17 - State Tools

5.18 - Progressive Web App Tools:

5.19 - GUI Development/Build Tools

5.20 - Templating/Data Binding Tools

Just Templating:

Templating and Reactive Data Binding:

Templating to Virtual DOM:

5.21 - UI Widget & Component Toolkits

On Web Platform:

React Specific, On Web Platform:

Native Desktop/Laptop/Netbook Apps via Web Platform (i.e. used with NW.js and Electron):

If you need a basic set of UI Widgets/Components start with Semantic UI. If you are building something that needs a grid, spreadsheet, or pivot grid you'll have to look at Kendo UI or Webix. Keep in mind that most of these solutions still require jQuery.

5.22 - Data Visualization (e.g., Charts) Tools

JS Libraries:

Widgets & Components:

Services (i.e. hosted data visualization services for embedding and sharing):

5.23 - Graphics (e.g., SVG, canvas, webgl) Tools

General:

Canvas:

SVG:

WebGL:

5.24 - Animation Tools

CSS and JavaScript Utilities:

Polyfills/Shims:

Animation References:

5.25 - JSON Tools

Online Editors:

Formatter & Validator:

Query Tools:

Generating Mock JSON Tools:

Online JSON Mocking API Tools:

List of public JSON API's:

Local JSON Mocking API Tools:

JSON Specifications/Schemas:

5.26 - Placeholder Content Tools

Images:

Device Mockups:

Text:

User Data:

5.27 - Testing Tools

Software Testing Frameworks:

Testing Assertions for Unit Testing:

Test Spies, Stubs, and Mocks for Unit Testing:

Hosted Testing/Automation for Browsers:

Integration/Functional Testing:

Browser Automation:

UI Testing Tools:

Automated dead link and error detectors:

HTTP Stubbing

5.28 - Front-End Data Storage Tools (i.e. Data storage solution in the client)

5.29 - Module Loading/Bundling Tools

5.30 - Module/Package Repository Tools

5.31 - Hosting Tools

General

Static

5.32 - Project Management & Code Hosting Tools

5.33 - Collaboration & Communication Tools

Code/GitHub Collaboration & Communication:

5.34 - Content Management Hosted/API Tools

Headless CMS Tools:

Self-hosted Headless CMS Tools:

Hosted CMS:

Static CMS Tools:

5.35 - Back-end/API tools

Data/back-end as a service aka BAAS:

Data/back-end

GraphQLApolloRelay* Falcor

User Management as a Service:

Search

5.36 - Offline Tools

For more tools look here.

5.37 - Security Tools

Coding Tool:

Security Scanners/Evaluators/Testers:

References:

5.38 - Tasking (aka Build) Tools

Tasking/Build Tools:

Opinionated Tasking/Build pipeline tools:

Before reaching for Gulp make sure npm scripts or yarn script won't fit the bill. Read, ["Why I Left Gulp and Grunt for npm Scripts"](https://medium.freecodecamp.com/why-i-left-gulp-and-grunt-for-npm-scripts-3d6853dd22b8#.nw3huib54 ""Why I Left Gulp and Grunt for npm Scripts"").

5.39 - Deployment Tools

5.40 - Site/App Monitoring Tools

Uptime Monitoring:

General Monitoring Tools:

5.41 - JavaScript Error Reporting/Monitoring

5.42 - Performance Tools

Reporting:

JS Tools:

Budgeting:

References/Docs:

Checklist:

5.43 - Tools for Finding Tools

5.44 - Documentation Generation Tools

Chapter 6. Front-end Communities, Newsletters, News Sites, & Podcasts

General Front-End Newsletters, News, & Podcasts:

HTML/CSS Newsletters:

JavaScript Newsletters, News, & Podcasts:

Front-End Communities

Notes:

  1. Need more Newsletters, News Sites, & Podcasts look at Awesome Newsletter.
  2. Find local front-end development communities by searching https://www.meetup.com/

Create Multi-Field Data Filters in Angular

Create Multi-Field Data Filters in Angular

Use Angular to create data filters that take multiple user inputs, and then use HTML to display the results of your TypeScript code.

In this tutorial, we are going to build something more advanced. It will be a multi-field data filter which will include simple inputs as well as selects. Let’s get started.

1. Creating a New Project

Let’s create a new project

ng new angular-data-filters
cd angular-data-filters

We also need to install a Bootstrap.

npm install bootstrap

To make it work in an Angular project, we need to add:

"node_modules/bootstrap/dist/css/bootstrap.min.css",

inside the style section of the Angular.json file.

2. Creating a Filter Pipe

We need to create a filter pipe in the first place. The pipe is a simple way to transform values in an Angular template.

ng generate pipe filter

After adding a couple of lines, we get our pipe to look like this:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(items: any[], value: string, prop: string): any[] {
if (!items) return [];
if (!value) return items;
return items.filter(singleItem =>
singleItem[prop].toLowerCase().startsWith(value.toLowerCase())
);
}
}

It’s important to note that if all fields are empty the data should not be filtered.

3. Creating a Search Component

To get started, use the below command:

ng generate component search

Let’s create a simple form that will include inputs for the first name, last name, job title, gender, and age from and age to fields. The last two fields will be used to create an age range.

export class SearchComponent implements OnInit {
form: FormGroup;
@Output() autoSearch: EventEmitter<string> = new EventEmitter<string>();
@Output() groupFilters: EventEmitter<any> = new EventEmitter<any>();
searchText: string = '';
constructor(private fb: FormBuilder,
private userService: UserService) {}
ngOnInit(): void {
this.buildForm();
}
buildForm(): void {
this.form = this.fb.group({
firstName: new FormControl(''),
lastName: new FormControl(''),
jobTitle: new FormControl(''),
gender: new FormControl(''),
agefrom: new FormControl(''),
ageto: new FormControl('')
});
}


<form novalidate
[formGroup]="form">
<h3>Group Filter</h3>
<div class="row">
<div class="col-md-3">
<input type="text"
formControlName="firstName"
class="form-control"
placeholder="First Name"
/>
</div>
<div class="col-md-3">
<input type="text"
formControlName="lastName"
class="form-control"
placeholder="Last Name"
/>
</div>
<div class="col-md-3">
<input type="text"
formControlName="Job Title"
class="form-control"
placeholder="Job Title"
/>
</div>
<div class="col-md-3 col-sm-3">
<select class="form-control"
formControlName="gender">
<option value="">Gender</option>
<option value="M">male</option>
<option value="F">female</option>
</select>
</div>
<div class="col-md-3">
<input type="text"
formControlName="agefrom"
class="form-control"
placeholder="age from"
/>
</div>
<div class="col-md-3">
<input type="text"
formControlName="ageto"
class="form-control"
placeholder="age to"
/>
</div>
<div class="col-md-3 col-sm-3">
<button class="btn btn-primary"
(click)="search(form.value)">Search</button>
</div>
</div>

You might notice from the above code that we didn’t use a template-driven form which is provided by Angular. In this tutorial, we used reactive forms. Now it’s time to add a code block for the search component in the TS file.

The last part for this component is implementing the search function:

search(filters: any): void {
Object.keys(filters).forEach(key => filters[key] === '' ? delete filters[key] : key);
this.groupFilters.emit(filters);
}
4. Building a User-List Component

To begin, enter the following command: 

ng generate component user-list

We will do it in the same way as we did for the search component, but, before that, we need data which will be fetched and displayed on the page. We are going to use JSON data that will add in the separate file and fetch it via a user service that will create with the following command.

ng generate service user

Here is where Angular observables com ein to solve our problem.

export class UserService {
setGroupFilter$ = new Subject<any>();
getGroupFilter = this.setGroupFilter$.asObservable();
constructor() {}
fetchUsers(): Observable<any> {
return of(USERS);
}
}

After making changes inside user service we can start working on the User-list component (UserListComponent). 

export class UserListComponent implements OnChanges {
@Input() groupFilters: Object;
@Input() searchByKeyword: string;
users: any[] = [];
filteredUsers: any[] = [];
constructor(private userService: UserService,
private ref: ChangeDetectorRef) { }
ngOnInit(): void {
this.loadUsers();
}
ngOnChanges(): void {
if (this.groupFilters) this.filterUserList(this.groupFilters, this.users);
}
filterUserList(filters: any, users: any): void {
this.filteredUsers = this.users;
const keys = Object.keys(filters);
const filterUser = user => {
let result = keys.map(key => {
if (!~key.indexOf('age')) {
if(user[key]) {
return String(user[key]).toLowerCase().startsWith(String(filters[key]).toLowerCase())
} else {
return false;
}
}
});
result = result.filter(it => it !== undefined);
if (filters['ageto'] && filters['agefrom']) {
if (user['age']) {
if (+user['age'] >= +filters['agefrom'] && +user['age'] <= +filters['ageto']) {
result.push(true);
} else {
result.push(false);
}
} else {
result.push(false);
}
}
return result.reduce((acc, cur: any) => { return acc & cur }, 1)
}
this.filteredUsers = this.users.filter(filterUser);
}
loadUsers(): void {
this.userService.fetchUsers()
.subscribe(users => this.users = users);
this.filteredUsers = this.filteredUsers.length > 0 ? this.filteredUsers : this.users;
}
}

In the above code, we include event emitters in the search component and also get the data from the user service. Then we implement a user data filtering feature based on options like the age range or gender and by other filters as well. The most important thing is that you can type in both uppercase and lowercase and it will work in both cases. Sometimes you might notice issues connected with character type in the other examples. 

So we need to create a simple HTML table for displaying the data.

<table class="table table-responsive">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Job Title</th>
<th>Age</th>
</tr>
<tbody>
<tr *ngFor="let user of filteredUsers | filter: searchByKeyword: 'name'">
<td>{{ user.firstName}}</td>
<td>{{ user.lastName}}</td>
<td>{{ user.gender}}</td>
<td>{{ user.jobTitle}}</td>
<td>{{ user.age}}</td>
</tr>
</tbody>
</table>

We have done a lot of work so far. Don’t worry, there's just a few steps left.

5. Creating a User Component

To start, use the below command:

ng generate component user

You might think, 'what’s the point of adding user components if there is already a user-list component included?'

User components will be a container for our search and user-list components.

<div class="container">
<br/>
<h1>List of Users</h1>
<hr/>
<app-search (groupFilters)="filters = $event"></app-search>
<br/>
<app-user-list [groupFilters]="filters"
[searchByKeyword]="searchText"></app-user-list>
</div>

Also, don't forget about user-routing.module.ts and user.module.ts

While it's a general Angular topic, you can choose your desired way to make the above components work together. However, for this tutorial, this approach was used:

import { RouterModule, Routes } from '@angular/router';
import { UserComponent } from './user.component';

const routes: Routes = [
{ path: '', component: UserComponent }
];

export const UserRoutes = RouterModule.forChild(routes);


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { UserComponent } from './user.component';
import { SearchComponent } from '../search/search.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserService } from '../../services/user.service';
import { FilterPipe } from '../../pipe/filter.pipe';
import { UserRoutes } from './user-routing.module';

@NgModule({
imports: [ CommonModule, FormsModule, ReactiveFormsModule, UserRoutes ],
declarations: [ UserComponent, SearchComponent, UserListComponent, FilterPipe ],
providers: [ UserService ]
})
export class UserModule { }

You can keep this two files inside the user folder. 

Thanks for reading

Further reading

☞ Angular 8 (formerly Angular 2) - The Complete Guide

☞ Angular & NodeJS - The MEAN Stack Guide

☞ The Complete Node.js Developer Course (3rd Edition)

☞ The Web Developer Bootcamp

☞ Best 50 Angular Interview Questions for Frontend Developers in 2019

☞ MEAN Stack Angular 8 CRUD Web Application

☞ Angular 8 Tutorial - User Registration and Login Example

☞ How to build a CRUD Web App with Angular 8.0

☞ Angular 8 Material Design Tutorial & Example


Originally published on https://dzone.com

How to Login and Registration ASP.NET Web API with Angular 8

How to Login and Registration ASP.NET Web API with Angular 8

In this article, we will learn the step by step process of creating login and registration pages in a Web API with Angular 8

In this article, we will learn the step by step process of creating login and registration pages in a Web API with Angular 8 using the following technologies:

  • ASP.NET Web API.
  • Angular 8.
  • SQL Server.
  • Bootstrap.

You may also like: Angular 8 HttpClient & Http Tutorial – Build and Consume RESTful API.

Prerequisites

  • Basic knowledge of Angular and Web API.
  • Visual Studio Code and Visual Studio IDE should be installed.
  • SQL Server Management Studio.
  • Nodejs should be installed.
Step 1

Open SQL Server Management Studio, create a database named Employee, and in this database, create a table. Give that table a name like Employeemaster.

CREATE TABLE [dbo].[Employeemaster](  
    [UserId] [int] IDENTITY(1,1) NOT NULL,  
    [UserName] [varchar](50) NOT NULL,  
    [LoginName] [varchar](50) NULL,  
    [Password] [varchar](50) NOT NULL,  
    [Email] [varchar](50) NULL,  
    [ContactNo] [varchar](15) NULL,  
    [Address] [varchar](50) NULL,  
    [IsApporved] [int] NULL,  
    [Status] [int] NULL,  
    [TotalCnt] [int] NULL,  
PRIMARY KEY CLUSTERED   
(  
    [UserId] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  

GO  

Now, create a stored procedure with the name, Usp_Login for adding the login functionality.

create proc  [dbo].[Usp_Login]  
@UserName varchar(50)='',  
@Password varchar(50)=''  
as begin  
    declare @UserId int =0,@TotalCnt int =0  
    select @UserId=UserId,@TotalCnt=TotalCnt from  Employeemaster um   
    where [email protected] and [email protected] and Status<>3 and IsApporved=1  
    if(@TotalCnt>=5)  
    begin  
       select 0 UserId,'' UserName,'' LoginName,'' Password,'' Email,'' ContactNo,   
    ''Address,0 IsApporved,-1 Status  
    end  
    if(@UserId>0)  
    begin  
        select UserId, UserName, LoginName, Password, Email, ContactNo,   
        Address, IsApporved, Status from  Employeemaster um   
        where [email protected]   
        --update  Employeemaster  set  Status=2 where [email protected]   

    end  
    else  
    begin  
       Update Employeemaster set @TotalCnt=TotalCnt+1    
       where [email protected] and Status=1 and IsApporved=1  
       select 0 UserId,'' UserName,'' LoginName,'' Password,'' Email,'' ContactNo,   
    ''Address,0 IsApporved,0 Status  
    end  
    end  
Step 2

Open Visual Studio and create a new project.

Create Registration And Login Page Using Angular 7 And Web API

_Create Registration And Login Page Using Angular 7 And Web API_

Change the name as LoginAPI and select Web API as its template.

Create Registration And Login Page Using Angular 7 And Web API

Step 3

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data. Create Registration And Login Page Using Angular 7 And Web API

Click on the ADO.NET Entity Data Model option and click Add. Create Registration And Login Page Using Angular 7 And Web API

Select EF designer from the database and click the Next button.

Create Registration And Login Page Using Angular 7 And Web API

Add the connection properties, select database name on the next page, and click OK. Create Registration And Login Page Using Angular 7 And Web API

Check the Tables and Stored procedure checkboxes. The internal options will be selected by default. Now, click the Finish button.

Create Registration And Login Page Using Angular 7 And Web API

Our data model is created now.

Step 4

Right-click on the Models folder and add two classes — Login and Response respectively. Now, paste the following codes in these classes.

using LoginAPI.Models;   
Step 5

Right-click on the Controllers folder and add a new controller. Name it as Logincontroller.

Add the following namespace in the Login controller.

[Route("Api/Login/createcontact")]  
       [HttpPost]  
       public object createcontact(Registration Lvm)  
       {  
           try  
           {  
               DemologinEntities db = new DemologinEntities();  
               Employeemaster Em = new Employeemaster();  
               if (Em.UserId == 0)  
               {  
                   Em.UserName = Lvm.UserName;  
                   Em.LoginName = Lvm.LoginName;  
                   Em.Password = Lvm.Password;  
                   Em.Email = Lvm.Email;  
                   Em.ContactNo = Lvm.ContactNo;  
                   Em.Address = Lvm.Address;  
                   Em.IsApporved = Lvm.IsApporved;  
                   Em.Status = Lvm.Status;  
                   db.Employeemasters.Add(Em);  
                   db.SaveChanges();  
                   return new Response  
                   { Status = "Success", Message = "SuccessFully Saved." };  
               }  
           }  
           catch (Exception)  
           {  

               throw;  
           }  
           return new Response  
           { Status = "Error", Message = "Invalid Data." };  
       }   

Now, add a method to insert data into the database for user registration.

[Route("Api/Login/UserLogin")]  
       [HttpPost]  
       public Response Login(Login Lg)  
       {  
           DemologinEntities DB = new DemologinEntities();  
           var Obj = DB.Usp_Login(Lg.UserName, Lg.Password).ToList<Usp_Login_Result>().FirstOrDefault();  
           if (Obj.Status == 0)  
               return new Response { Status = "Invalid", Message = "Invalid User." };  
           if (Obj.Status == -1)  
               return new Response { Status = "Inactive", Message = "User Inactive." };  
           else  
               return new Response { Status = "Success", Message = Lg.UserName };  
       }  
Step 6

Add a new method for logging into the Login controller with the following lines of code.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Web.Http;  
using LoginAPI.Models;  

namespace LoginAPI.Controllers  
{  
    public class LoginController : ApiController  
    {  

        //For user login   
        [Route("Api/Login/UserLogin")]  
        [HttpPost]  
        public Response Login(Login Lg)  
        {  
            DemologinEntities DB = new DemologinEntities();  
            var Obj = DB.Usp_Login(Lg.UserName, Lg.Password).ToList<Usp_Login_Result>().FirstOrDefault();  
            if (Obj.Status == 0)  
                return new Response { Status = "Invalid", Message = "Invalid User." };  
            if (Obj.Status == -1)  
                return new Response { Status = "Inactive", Message = "User Inactive." };  
            else  
                return new Response { Status = "Success", Message = Lg.UserName };  
        }  

        //For new user Registration  
        [Route("Api/Login/createcontact")]  
        [HttpPost]  
        public object createcontact(Registration Lvm)  
        {  
            try  
            {  
                DemologinEntities db = new DemologinEntities();  
                Employeemaster Em = new Employeemaster();  
                if (Em.UserId == 0)  
                {  
                    Em.UserName = Lvm.UserName;  
                    Em.LoginName = Lvm.LoginName;  
                    Em.Password = Lvm.Password;  
                    Em.Email = Lvm.Email;  
                    Em.ContactNo = Lvm.ContactNo;  
                    Em.Address = Lvm.Address;  
                    Em.IsApporved = Lvm.IsApporved;  
                    Em.Status = Lvm.Status;  
                    db.Employeemasters.Add(Em);  
                    db.SaveChanges();  
                    return new Response  
                    { Status = "Success", Message = "SuccessFully Saved." };  
                }  
            }  
            catch (Exception)  
            {  

                throw;  
            }  
            return new Response  
            { Status = "Error", Message = "Invalid Data." };  
        }  
    }  

}  

Complete Login controller

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");  
config.EnableCors(cors);  
Step 7

Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Create Registration And Login Page Using Angular 7 And Web API Open Webapiconfig.cs and add the following lines.

ng new login
Step 8

Create an Angular 8 project with a name "login" by using the following command.

npm install bootstrap --save
Step 9

Open Visual Studio Code, open the newly created project and add bootstrap to this project.

export class Register {  
    UserName:string;  
    LoginName:string;  
    Password:string;  
    Email:string;  
    ContactNo:string;  
    Address:string  
} 
Step 10

Now, create three components for the login page, registration page, and dashboard respectively. To create the components, open terminal and use the following commands.

  • ng g c login
  • ng g c register
  • ng g c dashboard

Create Registration And Login Page Using Angular 7 And Web API

Step 11

Create a class named "register". ng g class register Add the required properties in the class.

ng g s login 
Step 12

Create a service to call the Web API.

import { Injectable } from '@angular/core';  
import {HttpClient} from '@angular/common/http';  
import {HttpHeaders} from '@angular/common/http';  
import { from, Observable } from 'rxjs';  
import { Register } from "../app/register";  
@Injectable({  
  providedIn: 'root'  
})  
export class LoginService {  
  Url :string;  
  token : string;  
  header : any;  
  constructor(private http : HttpClient) {   

    this.Url = 'http://localhost:14812/api/Login/';  

    const headerSettings: {[name: string]: string | string[]; } = {};  
    this.header = new HttpHeaders(headerSettings);  
  }  
  Login(model : any){  
    debugger;  
     var a =this.Url+'UserLogin';  
   return this.http.post<any>(this.Url+'UserLogin',model,{ headers: this.header});  
  }  
   CreateUser(register:Register)  
   {  
    const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };  
    return this.http.post<Register[]>(this.Url + '/createcontact/', register, httpOptions)  
   }  
}  

Open the login service and import required packages and classes. Add the following lines of code in the login.service.ts file.

<div class="container" style="padding-top:40px;">  
    <div class="row">  
      <div class="col-md-6 mx-auto">  
        <div class="card mx-4">  
          <div class="card-body p-4">  
            <form [formGroup]="employeeForm" (ngSubmit)="onFormSubmit(employeeForm.value)">  
              <h1 style="text-align:center">Register</h1>  

              <div class="input-group mb-3">  

                <input type="text" class="form-control" placeholder="Username"  formControlName="UserName">  
              </div>  
              <div class="input-group mb-3">  
                <input type="text" class="form-control" placeholder="Loginname"  formControlName="LoginName">  
              </div>  
              <div class="input-group mb-3">  
                <input type="password" class="form-control" placeholder="Password"  formControlName="Password">  
              </div>  
              <div class="input-group mb-4">  
                <input type="text" class="form-control" placeholder="Email"  formControlName="Email">  
              </div>  
              <div class="input-group mb-4">  
                <input type="text" class="form-control" placeholder="Contact No"  formControlName="ContactNo">  
              </div>  
              <div class="input-group mb-4">  
                <input type="text" class="form-control" placeholder="Address"  formControlName="Address">  
              </div>  
              <button type="submit" class="btn btn-block btn-success">Add User</button>  
            </form>  
          </div>  
        </div>  
      </div>  
    </div>  
  </div>  
Step 13

Now, open register.component.html and add the following HTML code to design the registration form.

import { Component, OnInit } from '@angular/core';    
import { LoginService } from '../login.service';    
import {Register} from '../register';    
import {Observable} from 'rxjs';    
import { NgForm, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';    

@Component({    
  selector: 'app-register',    
  templateUrl: './register.component.html',    
  styleUrls: ['./register.component.css']    
})    
export class RegisterComponent implements OnInit {    
  data = false;    
  UserForm: any;    
  massage:string;    
  constructor(private formbulider: FormBuilder,private loginService:LoginService) { }    

  ngOnInit() {    
    thisthis.UserForm = this.formbulider.group({    
      UserName: ['', [Validators.required]],    
      LoginName: ['', [Validators.required]],    
      Password: ['', [Validators.required]],    
      Email: ['', [Validators.required]],    
      ContactNo: ['', [Validators.required]],    
      Address: ['', [Validators.required]],    
    });    
  }    
   onFormSubmit()    
  {    
    const user = this.UserForm.value;    
    this.Createemployee(user);    
  }    
  Createemployee(register:Register)    
  {    
  this.loginService.CreateUser(register).subscribe(    
    ()=>    
    {    
      this.data = true;    
      this.massage = 'Data saved Successfully';    
      this.UserForm.reset();    
    });    
  }    
}    

Step 14

Open register.componet.ts file and add following lines.

<div class="container" style="padding-top:60px;">  
  <div class="row">  
    <div class="col-md-6 mx-auto">  
      <div class="card-group">  
        <div class="card p-4">  
          <div class="card-body">  
            <form name="form" (ngSubmit)="login()" #f="ngForm">   
              <h1 style="text-align:center">Login</h1>  

              <div class="input-group mb-3">  
                <div class="input-group-prepend">  
                  <span class="input-group-text"><i class="icon-user"></i></span>  
                </div>  
                <input type="text" name="UserName" [(ngModel)]="model.UserName" class="form-control sty1" placeholder="Email" required>  
              </div>  
              <div class="input-group mb-4">  
                <div class="input-group-prepend">  
                  <span class="input-group-text"><i class="icon-lock"></i></span>  
                </div>  
                <input  type="password" name="Passward" [(ngModel)]="model.Password" class="form-control"  
               placeholder="Password">  
              </div>  
              <div>  
                  <p style="color:#E92626;font-size:20px;font-weight:normal" Class="success" align="left">  
                    {{errorMessage}}  
                  </p>  
                </div>  
              <div class="row">  
                <div class="col-6">  
                  <button type="submit" class="btn btn-primary px-4">Login</button>  
                </div>  
                <div class="col-6 text-right">  
                  <button type="button" class="btn btn-link px-0">Forgot password?</button>  
                </div>  
              </div>  

            </form>  
          </div>  
        </div>  
      </div>  
    </div>  
  </div>  
</div>  
Step 15

Open login.componet.html and add this HTML.

import { Component, OnInit } from '@angular/core';    
import { Router } from '@angular/router';    
import { LoginService } from '../login.service';    
 import { FormsModule } from '@angular/forms';    

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

  model : any={};    

  errorMessage:string;    
  constructor(private router:Router,private LoginService:LoginService) { }    

  ngOnInit() {    
    sessionStorage.removeItem('UserName');    
    sessionStorage.clear();    
  }    
  login(){    
    debugger;    
    this.LoginService.Login(this.model).subscribe(    
      data => {    
        debugger;    
        if(data.Status=="Success")    
        {       
          this.router.navigate(['/Dashboard']);    
          debugger;    
        }    
        else{    
          this.errorMessage = data.Message;    
        }    
      },    
      error => {    
        this.errorMessage = error.message;    
      });    
  };    
 }    

Open login.componet.ts and add following code.

<div>  
  <div class="row">  
    <div class="col-sm-12 btn btn-primary">  
        Welcome to DashBoard  
    </div>  
  </div>  
</div>  
Step 16

Now, open dashboard.component.html and add the following lines.

import { NgModule } from '@angular/core';    
import { Routes, RouterModule } from '@angular/router';    
import { DashboardComponent } from './dashboard/dashboard.component';    
import { LoginComponent } from './login/login.component';    
import { RegisterComponent } from './register/register.component';    

export const routes: Routes = [    
  {    
    path: '',    
    redirectTo: 'login',    
    pathMatch: 'full',    
  },    
  {    
    path: 'login',    
    component: LoginComponent,    
    data: {    
      title: 'Login Page'    
    }    
  },    
  {    
    path: 'Dasboard',    
    component: DashboardComponent,    
    data: {    
      title: 'Dashboard Page'    
    }    
  },    
  {    
    path: 'AddUser',    
    component: RegisterComponent,    
    data: {    
      title: 'Add User Page'    
    }    
  },    
];    

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

Now, open app-routing.module.ts file and add the following lines to create routing

import { NgModule } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 
import { DashboardComponent } from './dashboard/dashboard.component'; 
import { LoginComponent } from './login/login.component'; 
import { RegisterComponent } from './register/register.component'; 

export const routes: Routes = [ 
  { path: '', redirectTo: 'login', pathMatch: 'full', }, 
  { path: 'login', component: LoginComponent, data: { title: 'Login Page' } }, 
  { path: 'Dasboard', component: DashboardComponent, data: { title: 'Dashboard Page' } }, 
  { path: 'AddUser', component: RegisterComponent, data: { title: 'Add User Page' } }, 
]; 

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

export class AppRoutingModule { } 
Step 18

Now, let us run the project and redirect the URL to the "Add User" page.

Create Registration And Login Page Using Angular 7 And Web API

Enter the details and click on the "Add User" button.

Step 19

Now, run the project's default URL which takes us to the login page. Enter the username and password and click "Login".

Create Registration And Login Page Using Angular 7 And Web API

The following Page will be displayed.

Create Registration And Login Page Using Angular 7 And Web API

You may also like: Angular vs React vs Vue: Which one will be popular in 2020.

Summary

In this article, we discussed the process of Login and Registration page creation in an application with Angular 8 and Web API.

Thank you for reading ! If you enjoyed this article, please share it with others who may enjoy it as well.!

Full Stack Developers: Everything You Need to Know

Full Stack Developers: Everything You Need to Know

What is full stack developers? What is the full stack engineers job description? Are full stack developers paid more? How to hire full stack developers? Let’s find elaborative answers in this article!!!

What is full stack developers? What is the full stack engineers job description? Are full stack developers paid more? How to hire full stack developers? Let’s find elaborative answers in this article!!!

Full stack development is a buzz word nowadays. More and more companies are hiring full stack developers to save their time and cost. But most of the people still confused about the homonyms like Full stack developers, MEAN stack developers, MERN stack developers, etc. etc. etc.!!!

Being a Sr. software consultant, I come across some common questions on full stack coders on a day-to-day basis from businesses want web or mobile application development. Some questions are like:

*What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D
Okay so in this blog, I am going to answer some common queries of businesses related to full stack coders. Read the questionnaire in order to get the right and precise information about Full Stack Web Developers. Here we go:

Query 1: What is full-stack web development?

Full stack web development services include:

  1. Writing code for designing a website: Here, a full stack web developer uses popular programming languages like HTML, HTML5, CSS, and JavaScript.

  2. Writing code for receiving the information input from the users and saving it in databases: Here, a full stack developer uses various popular programming languages like PHP, Ruby on Rails and Python for creating algorithms and business logic in order to manipulate the data collected from the users.

  3. Managing Servers: Here, a full stack developer hosts the database on servers. Once your website is hosted on a server, anyone can access your website online.

Addition Information: Have a look at the complete application stack:

Query 2: What does a full stack web developer do?

A full stack web or mobile app developer work on the front end development as well as backend portions of web development or mobile app development. In other words, a full stack web developer is someone who can create a website that has an effective look and efficient functionality.

So Then… What is a Full Stack Engineer? A full stack engineer is a senior level developer role for someone with the skills of a full stack developer (as described above), but with the experience of project management in things like systems administration (managing, configuring, and maintaining computer systems and networks).

Query 3: What is the difference between a full stack developer and the MEAN stack developer?

A full stack developer has knowledge and experience of working with various stacks like MEAN, MERN, and LAMP. But it is not compulsory that a full stack developer is expert in all these stacks.

But a MEAN stack developer is expert in MEAN stack and has expertise in working on various technologies like MongoDB, ExpressJS, AngularJs, and NodeJS. All of these technologies have one thing common and that is, all of them use scripting language JavaScript.

Query 4: What’s the Difference Between Front End, Back End, and Full Stack?

A Front End developer (such as AngularJS developers, NodeJS developers, React Developers) writes code for web or mobile application and has the capability to manipulate the information present on the web/mobile app in order to make it look effective and appealing. Front End developer uses HTML, CSS, and JavaScript.

A Back End developer such as PHP developers, ASP.Net developers, or Python developers) writes code for receiving the information input from the user. Also, a Back End Developer saves this information in the database.

Full Stack Web Developer has experience of working in both the technologies- Front End as well as Back End of any application. Also, he/she has additional knowledge about MERN, MEAN, and LAMP.

Query 5: How a full stack web developer can help you enhance your business?

A full stack web app developer is proficient in both frontend and backend of any web or mobile applications and they can create a good looking and attractive web app for your business.

Also, the developer writes the code to give it efficient functionality. Not only this, a full stack web developer or Android mobile app developer or iOS mobile app developer hosts the database of your website on the server. So, by creating an attractive and efficient website, a full stack web developer helps you to get potential customers online.

Instead of hiring multiple coders, programmers or developers, some companies or businesses prefer professionals who can multitask. There’s a famous saying, “two is better than one.” So when you know both back-end and front-end, there is a higher chance and opportunity to land a job in the tech or software industry. In addition to this, based on the project need, a business can easily switch between front-end and back-end development.

Query 6: Which are some good full stack web development providers in India?

There are several companies providing full stack developers for hire basis where one can hire full stack web developers at affordable price rates. I have shortlisted some companies based on their portfolio, online reputation, cumulative annual growth rate, Google ranking, Clutch, and Goodfirms ratings, to name a few. Here are these companies:

*What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D> *What are full stack developers? Are they superhumans in the world of coding? :D#### Query 7: Which programming languages a full stack developer know?

A full stack web developer has good experience of working with HTML, CSS, JavaScript (such as AngularJS development, Nodejs Development, VueJS development, and Reactjs Development) as well as various backend languages like PHP web development, ASP.Net web development, Ruby web development, and Python web development.

Query 8: What is the average pay of the full stack web developers in India or will it cost high for hiring?

According to a pilot conducted by Indeed, the average salary for a Full Stack Developer in India is 6.25 lakhs per annum. It implies that a Full Stack Developer in India makes around 52 thousand per month.

Query 9: Why is hiring a full stack web developer better than normal web developers?

A full stack developer has the knowledge and experience of working with Front end web development as well as Backend web development. Moreover, full stack developer has knowledge about technologies like LAMP, MERN and MEAN.

But if you hire a normal web developer, then this web developer may not be having knowledge about so many technologies. A normal web developer can be either a front end developer or a back end developer.

So, instead of hiring two different developers, one can hire a full stack developer that will be solely responsible for managing the website or application development work from start to the end.

Query 10: Why should one outsource its full stack web development?

There are various full stack web development providers that offer robust Full Stack web development services. Outsourcing Full Stack Web Development can help to get the best services and that too at the said time deadline.

Moreover, it saves a lot of time that a business can put into making strategies for marketing and sales.

We performed deep research before putting all these selected questions in this questionnaire. We hope that these questions help you in solving all the queries that you have regarding Full Stack Web Developers.

Wrapping Up:

I hope I have cleared all doubts of businesses and companies related to hiring full stack developers. Full stack developers definitely will help you save money and time, but you have to pay more to full stack developer(obviously).

If you have any other query related to full stack programmers and coders, feel free to ask me through the comment box, and I will try to answer it as soon as possible by adding more information here.