How to Create Components in Angular 9

How to Create Components in Angular 9

In this article we will learn how to Create Components in Angular 9, use the generate component command of Angular CLI, or its shortcut shortcut command, for creating Angular components in your project.

We can think of Angular Components like LEGO pieces. We create a component once but can use them multiple times in different
An Angular app is a tree structure consisting of all those components that we create, like how we make a Lego Structure from little Lego pieces.

Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components.— Angular official docs

In this article we will learn how to Create Components in Angular 9, use the generate component command of Angular CLI, or its shortcut shortcut command, for creating Angular components in your project.

How to Use ng generate component or ng g c

Let's assume we want to create a Angular component named family
Open a new command-line interface, navigate into the root of your Angular project and run the following command:

$ ng generate component family

Or you can also run the following command:

$ ng g c family

Angular CLI will generate 4 files for the component in the src/app folder of your project:

/family/family.component.ts       # Component class
  /family/family.component.html     # Component template
  /family/family.component.css      # Component styles
  /family/family.component.spec.ts  # Component tests

We can also customize where the component's files are placed.

Angular CLI adds the component to the declarations array of the module.

@NgModule({
  // [...]
  declarations: [ AppComponent, FamilyComponent ]
  // [...]
})
export class AppModule { }

This will allow FamilyComponent in any component in the AppModule.

How to Customize the Output of ng generate component

By default the ng generate component or ng g c commands, generate a folder and four files for the component. But you can change the default behavior if you want in two ways:

Using flags with the command,
Using the angular.json configuration file.

Using Flags with the ng generate command
Let's generate an about component without a subfolder and without the specification file.

Head back to the terminal and run the following command:

$ ng generate component about --flat=true --spec=false


Using the angular.json File

Let's now see by example how to configure the CLI from the angular.json file to not generate .spec.ts file for a component.

Go back to your terminal and run the following command:

$ ng config [email protected]/angular:component.spec false


How to Set the Component's Folder

You can aso define the folder of the component by specefying the path as follows:

$ ng generate component components/contact

This will create the contact component inside the components folder which will also be created if it doesn't exist inside the src/app folder of the project.

Manually Creating Components

You can also create Angular components manually by creating the necessary files and add the component's class to the declarations array of the module where it should be used.

Angular CLI Naming Conventions

When you create an Angular component with Angular CLI, it will follow these conventions:

The Component suffix is added to the name you submit for the component.
The app- prefix is added to the selector of the component.
The name of the component class is in upper camel case,

That's what this article wants to share with you on how to create components in Angular using the ng generate component command or its ng shortcut shortcut command.

Learn More

Thanks for reading !

Upgrade Angular 8/7 to Angular 9 With Ng Update & Angular CLI v9

Upgrade Angular 8/7 to Angular 9 With Ng Update & Angular CLI v9

Updating Angular CLI to v9 and upgrading your project to Angular 9 from v8/7 is now easier than ever before, thanks to all the work that has been done in version 9 and the ng update command which allows you to update specific versions and...

Updating Angular CLI to v9 and upgrading your project to Angular 9 from v8/7 is now easier than ever before, thanks to all the work that has been done in version 9 and the ng update command which allows you to update specific versions and dependencies.

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.

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!