How to Create an Angular Web App Quickly for Developers | Angular 8 Tutorial

How to Create an Angular Web App Quickly for Developers | Angular 8 Tutorial

A comprehensive step by step Angular 8 tutorial on how to create an Angular web app quickly

In this Angular 8 tutorial, we will show you a basic and quick way to create an Angular web app. This tutorial does not just show a simple Hello world or a default Angular generated the page, but more than that we will show using the interaction with the array of objects data in the separate file. Also, we will show you how to use a basic Angular Material, Routing, and Navigation with the parameters.

Angular 8 Tutorial | FormArray In Angular 8 with Example

Angular 8 Tutorial | FormArray In Angular 8 with Example

The Form Array is a way to group Form controls in Angular. We can group FormControl in Angular forms in two ways. One is using the FormGroup and the other one is FormArray. The difference is how they implement it...

The Form Array is a way to group Form controls in Angular. We can group FormControl in Angular forms in two ways. One is using the FormGroup and the other one is FormArray. The difference is how they implement it. In FormGroup controls becomes a property of the FormGroup. Each control is represented as key-value pair. While in Form Array, the controls become part of an array

Because it is implemented as Array, it makes it easier dynamically add controls.

FormArray Example in Angular 8

Angular 8 FormArray is a bit like FormGroup, and it’s used in a very similar way, the difference being that it’s used as an array that envelops around an arbitrary amount of FormControl, FormGroup or even other FormArray instances.FormArray is a class of @angular/forms module.

Constructor

constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[])

The controls parameter is required, and it is an array of child controls. Each child control is given the index where it is registered.

The validatorOrOpts is an optional parameter. It is an asynchronous validator function, or an array of such functions, or an AbstractControlOptions object that contains validation functions and the validation trigger.

The asyncValidator is an optional parameter. It is a single async validator or array of async validator functions.

Properties

Angular FormArray has two properties.

  1. control: The control is an array of child controls. Each child control is given the index where it is registered.
  2. length: It is a length of the control array.

Import ReactiveFormsModule

Type the following command to create a new Angular project.

ng new angforms

Install Bootstrap 4 using the following command.

➜  angforms git:(master) ✗ npm install bootstrap --save
npm WARN [email protected] requires a peer of [email protected]^5 || ^6 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of [email protected] - 3 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of [email protected]^1.16.0 but none is installed. You must install peer dependencies yourself.

+ [email protected]
added 1 package from 2 contributors and audited 19367 packages in 12.498s

14 packages are looking for funding
  run `npm fund` for details

found 2 moderate severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details
➜  angforms git:(master) ✗

Now, add the following code inside the angular.json file.

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

Now, write the following code inside the app.module.ts file.


// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We have imported ReactiveFormsModule because we are using the Reactive Forms approach and not a template-driven approach.

Angular 8 form classes

Creating a form using FormControl, FormGroup, and FormArray are said to be the reactive forms. They use an ng module as ReactiveFormsModule.

For every form control such as text, checkbox, radio button, we need to create an instance of FormControl in our class.

For instance, let’s say we need to create an instance of the name field.

name = new FormControl();


In our HTML template, you can use the following code.

<input [formControl]="name">

Okay, now write the following code inside the app.component.ts file.


// app.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup, FormArray, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  angForm = new FormGroup({
    names: new FormArray([
      new FormControl('', Validators.required),
      new FormControl('', Validators.required),
    ])
  });
}

In the above code, we have imported four angular classes.

  1. FormControl: FormControl is a class that is used to get and set values and validation of the form control such as <input> and <select> tag.

  2. FormGroup: FormGroup has a role in tracking the value and validity state of a group of FormControl.

  3. FormArray: FormArray tracks a value and validity state of the array of FormControl, FormGroup, or FormArray instances.

  4. Validators: Validators provides a set of built-in validators that can be used by form controls.

Also, we need to define one Getter method for the names array.

Write the following code inside the app.component.ts file.

// app.component.ts

get names(): FormArray {
    return this.angForm.get('names') as FormArray;
}

It will return all the names as FormArray.

Create form class instances

Then we have created a FormGroup instance called angForm.

We have passed the FormArray instance, which consists of two FormControls.

We will iterate names array in our UI. Write the following code inside the app.component.html file.

<!-- app.component.html -->

<div formArrayName="names">
  <div *ngFor="let name of names.controls; index as idx">
     <input [formControlName]="idx" placeholder="Enter a Name">
     <label *ngIf="name.invalid" [ngClass] = "'error'"> Name is required. </label>
  </div>
</div>

When we submit the form, we can fetch values as given below.

Write the following code inside the app.component.ts file.


// app.component.ts

onFormSubmit(): void {
    for(let i = 0; i < this.names.length; i++) {
      console.log(this.names.at(i).value);
    } 
  }

Dynamically add and remove fields

On the instance of FormArray, i.e., names, we will call controls that will return an array of FormControl instances. Now to add a form control at run time, we need to use the push() method of FormArray.

To remove from FormArray, we will use removeAt() function and pass the index parameter. We can remove the form control at run time; we need to use the removeAt() method of FormArray.

We are also adding validation while creating FormControl instances.

// app.component.ts

addNameField() { 
    this.names.push(new FormControl('', Validators.required)); 
}

deleteNameField(index: number) {
    if (this.names.length !== 1) { 
      this.names.removeAt(index); 
    }
}

We are also adding validation when adding a new FormControl.

That means a new, dynamically added text field has required validation.

So, our app.component.ts file looks like this.


// app.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup, FormArray, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  angForm = new FormGroup({
    names: new FormArray([
      new FormControl('', Validators.required),
      new FormControl('', Validators.required),
    ])
  });

  get names(): FormArray {
    return this.angForm.get('names') as FormArray;
  }
  onFormSubmit(): void {
    for (let i = 0; i < this.names.length; i++) {
      console.log(this.names.at(i).value);
    }
  }
  addNameField() {
    this.names.push(new FormControl('', Validators.required));
  }

  deleteNameField(index: number) {
    if (this.names.length !== 1) {
      this.names.removeAt(index);
    }
    console.log(this.names.length);
  }
}

Now, write our final code inside the app.component.html file looks like the below.


<!-- app.component.html -->

<div class="container">
<h3>Angular 8 FormArray Example</h3>
<form [formGroup] = "angForm" (ngSubmit)="onFormSubmit()">
  <div formArrayName="names">
    <div *ngFor="let name of names.controls; index as idx" class="form-group">
      <input [formControlName]="idx" placeholder="Enter a Name" class="form-control">
      <label *ngIf="name.invalid" [ngClass] = "'error'"> Name is required. </label>
      <button type="button" (click)="addNameField()" class="btn btn-success" [ngClass] = "'pad'">Add More Names</button>
      <button (click)="deleteNameField(idx)" class="btn btn-danger">Delete</button>
    </div>
  </div> 
  <div>
    <button type="submit" class="btn btn-primary">Send</button>
  </div>
</form>
</div>

Our CSS code inside the app.component.css file is the following.

.error{
  color: red;
  font-size: 20px;
  margin-top: 10px;
  margin-right: 10px;
}
.pad{
  margin-right: 10px;
  margin-top: 10px;
}

Now, when you start typing your name at a particular textbox, for that specific textbox, the error will disappear.

When the user submits the form, we will get all the dynamically added textbox values.

We can also add or remove the textboxes dynamically, which is really cool.

So, if you want a functionality in which you need to add dynamic fields in Angular 8, then this is your perfect solution.

See the output.

Okay, now let’s see some of the functions of Angular 8 FormArray.

Angular 8 FormArray Methods

FormArray.at()
Get the AbstractControl at the given index in the array. It is an index in the array to retrieve the control.

FormArray.push()
The push() function inserts a new AbstractControl at the end of the array. We have seen the push() method in our dynamic insert fields example.

FormArray.insert()
The insert() function inserts a new AbstractControl at the given index in the array.

Form.removeAt()
The removeAt() function removes the control at the given index in the array. We have seen the removeAt() method in our dynamic remove fields example.

You can learn more about the functions of FormArray here

Learn More

This tutorial is the end, if you find it helpful to share it with everyone. Thanks for reading!

How to Implement AES Encrypt and Decrypt Data in Angular 8

How to Implement AES Encrypt and Decrypt Data in Angular 8

In this article, You’ll learn how to implement AES encryption and decryption in Angular 8 while developing an application.

Introduction

In this article, You’ll learn how to implement AES encryption and decryption in Angular 8 while developing an application.

Concepts

The AES is the advanced encryption standard. So, these algorithms have been the standard of encryption for organizations like the NSA and anyone else that wants to hide their data. So, it’s a critical part of the computer science curriculum. that you should understand if you’re a software developer.

Actually, DES and AES were both developed to solve the same problem in 1971. this algorithm was invented by two Belgian cryptographers, Vincent Rijmen and Joan Daemen. IBM was the inventor of this algorithm called DES. it gradually became insecure and crackable as computer software or as computer hardware.

In the late 1990s, the government the NSA, in particular, decided that they needed to have an improved algorithm. so they put open a worldwide search and took ideas from fifteen different groups. then they create something that has been a standard for now over 20 years so these algorithms are known as symmetric ciphers.

You would have a single password or key that would encrypt your document and then that same key is going to unlock the document. so that key is important the alternative to symmetric encryption is called asymmetric encryption.

When to use AES Encryption

1. If you want to encrypt confidential data into a decryptable format, for example – if you need to send some sensitive data via e-mail.

2. The decryption of the encrypted data is possible only when you know the right password.

Now, It is very easy to implement the AES encryption and decryption in Angular 8 with the help of crypto-js.

Let’s, create a new project with the below command.

ng new EncryptionDescryptionSample

After that, we need to install a crypto.js file, by the below command.

npm install crypto-js --save  

For better responsive UI, we also install bootstrap by the below command.

npm install bootstrap --save  

Now, Let’s go an open “app.component.html” file and replace the existing code with the following code.


<h1 class="text-center">Encrypt-Decrypt with AES</h1>  
<br>  
<div>  
  <div class="row">  
    <div class="col-sm-6">  
      <button type="button" class="btn btn-primary btn-lg btn-block">  
        Encryption  
      </button>  
      <br>  
      <div class="form-group">  
        <label for="txtTextToConvert">Plain Text</label>  
        <input type="text" class="form-control" placeholder="Enter text you want to encrypt" [(ngModel)]="plainText">  
      </div>  
  
      <div class="form-group">  
        <label for="txtPassword">Password</label>  
        <input type="password" class="form-control" placeholder="Enter encryption password" [(ngModel)]="encPassword">  
      </div>  
      <textarea class="form-control" readonly rows="3">{{conversionEncryptOutput}}</textarea>  
      <br>  
      <button type="button" class="btn btn-success float-right" (click)="convertText('encrypt')">Encrypt</button>  
    </div>  
    <div class="col-sm-6">  
      <button type="button" class="btn btn-dark btn-lg btn-block">  
        Decryption  
      </button>  
      <br>  
      <div class="form-group">  
        <label for="txtTextToConvert">Encrypted Text</label>  
        <input type="text" class="form-control" placeholder="Enter text you want to decrypt" [(ngModel)]="encryptText">  
      </div>  
  
      <div class="form-group">  
        <label for="txtPassword">Password</label>  
        <input type="password" class="form-control" placeholder="Enter decryption password" [(ngModel)]="decPassword">  
      </div>  
      <textarea class="form-control" readonly rows="3">{{conversionDecryptOutput}}</textarea>  
      <br>  
      <button type="button" class="btn btn-success float-right" (click)="convertText('decrypt')">Decrypt</button>  
    </div>  
  </div>  
</div>

After that, open “app.component.ts” file and write the following code, we used the Encrypt method of AES and passed our plain text with a password to encrypt the string. then Similarly, we used the Decrypt method of AES and passed our encrypted text with a password to decrypt the string. Be assured that both times, your password we’ll be the same. so, using both of these methods, you just need to import “CryptoJS” from crypto-js libraries.

import { Component } from '@angular/core';  
import * as CryptoJS from 'crypto-js';  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'EncryptionDecryptionSample';  
    
  plainText:string;  
  encryptText: string;  
  encPassword: string;  
  decPassword:string;  
  conversionEncryptOutput: string;  
  conversionDecryptOutput:string;  
    
  constructor() {  
  }  
  //method is used to encrypt and decrypt the text  
  convertText(conversion:string) {  
      if (conversion=="encrypt") {  
        this.conversionEncryptOutput = CryptoJS.AES.encrypt(this.plainText.trim(), this.encPassword.trim()).toString();  
      }  
      else {  
        this.conversionDecryptOutput = CryptoJS.AES.decrypt(this.encryptText.trim(), this.decPassword.trim()).toString(CryptoJS.enc.Utf8);  
       
    }  
  }  
}  

Now, Run the project by using the below command.

ng serve --o

Here is the output.

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you !

How to Use Cookies in Angular for Storing user’s Credentials

How to Use Cookies in Angular for Storing user’s Credentials

In this post, I will be explaining about using Cookies in Angular for Storing user’s Credentials

By using cookies we are going to store the user's login data, if the user's credentials are valid, then it will be directed to the Dashboard page.

In this post, I will be explaining about Angular cookies. So what is a cookie? Cookies are like a small package of information that is stored by the user’s browser. Cookies persist across multiple requests and browser sessions that should be set so that they can be a great method for authentication in web applications. Sometimes we will have some queries about which is to be used -- either local storage or cookies? Before that, I like to say that the cookies and local storage serve different purposes.

The local storage can be read on the client-side, whereas the cookies are being read on the server-side. The biggest difference is the data size is about to store, the local storage will give more space to store, whereas the cookie is limited by the size of to store.

As I said above the cookies are used on the server-side whereas the local storage is used on the client-side. The local storage is a way of storing the data in the client’s PC, by saving the key/ value pair in a web browser with no expiration date. We will discuss about using local storage in the next article, so coming to the point, as I said the cookies are a kind of small file that are stored on the user’s browser.

The cookie is a small table which will contain key and data values so, by using this it will be very useful to carry information from one session to another session. Once we are about to store data on the server without using cookies then it will be difficult to retrieve a particular user’s information without a login on each visit to that website.

So far we have seen about the overview of a cookie and the usage of it. Now in this article, I will explain about storing the username and password of a static user in the cookie table. So, I have created two components, namely the login component and dashboard component, and I have set a static username and password in authservice.ts file.

So, when a user logs in to the login form by providing his user’s credentials the authservice checks the input and redirects the user to the dashboard if the user’s credentials are valid. If the user’s credentials are not valid it will alert by throwing enter valid email or password. And if the dashboard page is being accessed by unauthorized usage the page will be redirected to the login page automatically.

Setting up

In order to use cookies in Angular, we need to install the Angular cookie library by using the following npm package manager.

npm install ngx-cookie-service –save

After installing the package manager, we need to import the cookie service in the inside of our modules.

I have used the ng zorro library UI for form design, and you can find more information about ng zorro from the following link. The next step is to design a login form. So, open login.component.html file and replace the following code.

<form fxFill #Login="ngForm" (ngSubmit)="onsubmit()">  
    <div nz-row>  
        <div nz-col nzMd="12" nzXs="24">  
            <hr />  
            <nz-form-item>  
                <nz-input-group>  
                    <div nz-col nzMd="11" nzXs="8">  
                        <nz-input-group nzPrefixIcon="user">  
                            <input type="text" nz-input name="Login_name" placeholder="User Name" id="userName"  
 
#userName="ngModel" [(ngModel)]="Obj.username">  
                            </nz-input-group>  
                            <div *ngIf="Login.submitted && userName.errors" style="color: red">  
                                <div *ngIf="userName.hasError('required')">  
  
Login ID is required  
  
</div>  
                            </div>  
                        </div>  
                    </nz-input-group>  
                </nz-form-item>  
                <nz-form-item>  
                    <div nz-col nzMd="11" nzXs="8">  
                        <nz-input-group nzPrefixIcon="lock">  
                            <input type="password" nz-input name="user_password" placeholder="Password"  
  
id="password" #password="ngModel" [(ngModel)]="Obj.password">  
                            </nz-input-group>  
                            <div *ngIf="Login.submitted && password.errors" style="color: red">  
                                <div *ngIf="password.hasError('required')">  
  
Password is required  
  
</div>  
                            </div>  
                        </div>  
                    </nz-form-item>  
                    <div class="button">  
                        <button nz-button nzType="primary">  
  
submit  
  
</button>  
                    </div>  
                </div>  
            </div>  
        </form>  

Now open login.component.ts file and replace the following code in it.

import {  
    Component,  
    OnInit  
} from '@angular/core';  
import {  
    FormGroup  
} from '@angular/forms';  
import {  
    AuthService,  
    User  
} from '../services/authservice.service';  
import {  
    Router,  
    ActivatedRoute  
} from '@angular/router';  
import {  
    CookieService  
} from 'ngx-cookie-service';  
@Component({  
    selector: 'nz-demo-card-simple',  
    templateUrl: './login.component.html'  
})  
export class LoginComponent implements OnInit {  
    Obj: User;  
    constructor(private srvLogin: AuthService, private router: Router, public activatedRoute: ActivatedRoute, private cookieService: CookieService) {  
        this.Obj = new User();  
    }  
    ngOnInit(): void {}  
    onsubmit(): void {  
        this.cookieService.set('username', this.Obj.username);  
        this.cookieService.set('password', this.Obj.password);  
        console.log(this.cookieService.get('username'));  
        console.log(this.cookieService.get('password'));  
        const a = this.Obj;  
        if (this.srvLogin.checkLogValues(this.Obj)) {  
            this.srvLogin.isloggedin = true;  
            console.log(this.srvLogin.isloggedin);  
            this.router.navigate(['/dashboard']);  
        }  
    }  
}  

The next point is to create an authentication service, we can create a service file by using the syntax.

ng generate service AuthService

The service name which I have given is Authservice and the service will be created and I have provided a default static username and password in service file so that the validation will be executed and redirected to another page (dashboard page) if the user’s credentials are being valid. Open Authservice service.ts file and replace the following code and import it in both service and as well in app-module.ts file.

import {  
    Injectable  
} from '@angular/core';  
import {  
    HttpClient  
} from '@angular/common/http';  
import {  
    CookieService  
} from 'ngx-cookie-service';  
@Injectable({  
    providedIn: 'root'  
})  
export class AuthService {  
    private username = 'vidya';  
    private password = '123456';  
    isloggedin = false;  
    constructor(private http: HttpClient) {}  
    checkLogValues(value: User): boolean {  
        if (this.username === value.username && this.password === value.password) {  
            console.log(this.username);  
            console.log(this.password);  
            // alert('Login valid');  
            return true;  
        } else {  
            alert('please enter valid data');  
            return false;  
        }  
    }  
}  
export class User {  
    username: string;  
    password: string;  
}  

After that create a component named as dashboard and open dashboard.component.html file and replace the following code.

<h3>Hello {{userDisplayName}} you are in Dashboard </h3>  
<div style="text-align:right">  
   <button nz-button nzType="danger" (click)="logout()">Logout</button>  
</div>  

The next step is to open dashboard.component.ts file and replace the following code inside it.

import {  
    Component,  
    OnInit  
} from '@angular/core';  
import {  
    AuthService,  
    User  
} from '../services/authservice.service';  
import {  
    Router,  
    ActivatedRoute  
} from '@angular/router';  
import {  
    CookieService  
} from 'ngx-cookie-service';  
@Component({  
    selector: 'dashboard',  
    templateUrl: './dashboard.component.html'  
})  
export class DashboardComponent implements OnInit {  
    Obj: User;  
    [x: string]: any;  
    userDisplayName = '';  
    password = '';  
    constructor(private srvLogin: AuthService, private router: Router, public activatedRoute: ActivatedRoute, private cookieService: CookieService) {  
        this.Obj = new User();  
        this.userDisplayName = this.cookieService.get('username');  
        this.password = this.cookieService.get('password');  
        this.Obj.username = this.userDisplayName;  
        this.Obj.password = this.password;  
        if (!srvLogin.checkLogValues(this.Obj)) {  
            router.navigate(['/login']);  
        }  
    }  
    ngOnInit(): void {}  
    logout(): void {  
        this.router.navigate(['/login']);  
        this.cookieService.deleteAll();  
    }  
}  

The following next step is to log in to the dashboard by providing the user’s credentials and after the valid login, we can see the user’s name in dashboard as a welcome note by using the user’s login name. So, after entering into the dashboard page open the developer’s tool in the browser and navigate -> Application and select cookies from storage. So, on that, we can see the user name and password have been stored in the cookie table.

So  far we have seen about storing the user’s details in the cookie table and now we can take an overview on clearing the cookies in the cookie table; for that use deleteall() method for clearing the cookies table if  the user is about to click-> logout button.

Conclusion

In this post, we have seen about using cookies in Angular for storing user’s credentials. I hope this article will be useful for you.