Angular 8 Checkbox : Angular 8 Checkbox Tutorial with Example

Angular 8 Checkbox : Angular 8 Checkbox Tutorial with Example

A checkbox is also known as the tick-box and it is a Graphical User Interface widget that allows a user to choose one or many possible options. In this article, we will build a checkbox list with Angular but create it dynamically from a list.

If you have been creating any type of applications till now, you are already aware of the huge significance that a checkbox holds. Not only does it makes the input of data easier to any platform, but it also facilitates the quick sorting of data as it often comes packaged with the list feature.
A checkbox is also known as the tick-box and it is a Graphical User Interface widget that allows a user to choose one or many possible options.
In this article, we will build a checkbox list with Angular but create it dynamically from a list.

Let’s get started!

Install Angular 8 project

If you do not know how to update angular cli, then check out the update angular 8 cli tutorial
If you are unfamiliar with Angular, then check out the Angular 8 tutorial.

Now, create a brand new angular project using the following command.

ng new ang


Now, go inside the folder and open the project in Visual Studio Code.

The next step is to import FormsModule and ReactiveFormsModule inside the app.module.ts file.


// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

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

Define data to show checkbox

Inside the app.component.ts file, we will define the following data.


// app.component.ts

...
cartoonsData: Cartoon[] = [
    { id: 0, name: 'Tom and Jerry' },
    { id: 1, name: 'Rick and Morty' },
    { id: 2, name: 'Ben 10' },
    { id: 3, name: 'Batman: The Animated Series' }
  ];
...

So, in the checkbox, we will display these name values from the above array.
The user then selects their favorite cartoon and submit the form and then in the submit() function, and we will get those selected values.

Define the HTML view for checkbox

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


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

<div style="margin-top: 30px">
<form [formGroup]="form" (ngSubmit)="submit()">
  <div *ngFor="let cartoon of cartoonsData">
    <input type="checkbox" (change)="onChange(cartoon.name, $event.target.checked)" />
    {{ cartoon.name }}
  </div>
  <button>submit</button>
</form>
</div>

In the above code, we have attached a formGroup directive to form and also use the ngSubmit event.

So, when the user clicks on the submit button, the ngSubmit() event fires, and it calls the submit() function.

Then we have used the ngFor directive to display the dynamic checkbox list with the onChange() event.

If the user clicks the checkbox, then change() event will fire, and then cartoon name and checked values are passed to that onChange() function that is associated with that event.

We will define the onChange() function inside the app.component.ts file.

Don’t save the file and go to the browser if you are running the project because you will get the error.
Now, let’s head to the last step.

Define onChange() and submit() function

Okay, so now we have our app.component.html and app.module.ts file complete.

Now, we need to define two main functions to track the checkbox values and get those checked values.

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


// app.component.ts

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

export interface Cartoon {
  id: number;
  name: string;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  form: FormGroup;
  cartoonsData: Cartoon[] = [
    { id: 0, name: 'Tom and Jerry' },
    { id: 1, name: 'Rick and Morty' },
    { id: 2, name: 'Ben 10' },
    { id: 3, name: 'Batman: The Animated Series' }
  ];

  constructor(private fb: FormBuilder) { }

  onChange(name: string, isChecked: boolean) {
    const cartoons = (this.form.controls.name as FormArray);

    if (isChecked) {
      cartoons.push(new FormControl(name));
    } else {
      const index = cartoons.controls.findIndex(x => x.value === name);
      cartoons.removeAt(index);
    }
  }

  ngOnInit() {
    this.form = this.fb.group({
      name: this.fb.array([])
    });
  }

  submit() {
    console.log(this.form.value.name);
  }
}

In the above code, first, we have imported four forms modules from forms packages.

  1. FormBuilder: It creates the AbstractControl from a user-specified configuration.

  2. FormGroup: It tracks the value and validity state of a group of FormControl instances

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

  4. FormControl: It tracks the value and validation status of an individual form control.

Then we have defined the interface Cartoon, which is the type of data of the checkbox.
Then defined a constructor and created FormBuilder instance.

In the next step, we have defined the onChange() function, which takes two parameters.

  1. name

  2. isChecked

If the particular checkbox values are checked, then we are pushing the checked values to the FormArray and removing the values if the user unchecks the checkbox options.

Inside the submit() function, we are getting the checked values array and log it in the console.

Finally, see the output.

You can see in the console that an array of two values are logged, which means we have successfully got the checked the values inside the array.

Now, we can send that array to the server and save it inside the database.

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 !

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 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.