How to Use @Input() And @Output() Decorator in Angular

How to Use @Input() And @Output() Decorator in Angular

This post, we have learn how to pass data from parent to child component and vice versa, and which decorators are more responsible for doing this task, called @Input() and @Output() decorator.

Introduction

In this article, I am exploring two very important points, related to Angular 2 + version, which the part of Parameter Decorator and these points are called @Input and @Output decorators.  Both are used to transform the data from one component to another component.  Or, you can say pass the different types of data from parent to child component and child to parent component.  Or, in a simple way transform/exchange data between two-component.

Let's explore each, one by one.

@Input Decorator

@Input is a decorator to mark a property as an input.  @Input is used to define an input property, to achieve component property binding.  @Inoput decorator is used to pass data (property binding) from parent to child component.  The component property should be annotated with @Input decorator to act as input property.

Let's explore it practically.

I have created an angular application which is AngApp.  I have created two components.  They are app components and student components.  I will transfer the data from parent to child component, using @Input decorator.  I am assuming my, app-component is the parent component and student-component is the child component.

To make the parent-child relation, keep the instance (selector of student component) of student component inside the template URL (app.component.html) of app component.

Open app.component.html:  Inside this file, we keep an instance of student component.

Example

<div> <app-student></app-student></div> 

In the above image, the selected area is the child component.

Now, we want to send the message from parent to child component.

Let's open the parent component's .ts file (app.component.ts) and declare a variable inside AppComponent class, to store the message.  This message is received by the child component.

myInputMessage:string ="I am the parent comppnent"  

import { Component, Input, OnInit } from '@angular/core';  
  
@Component({  
   selector: 'app-student',  
   templateUrl: './student.component.html',  
   styleUrls: ['./student.component.css']  
})  
  
export class StudentComponent implements OnInit {  
@Input() myinputMsg:string;  
  
constructor() { }  
  
ngOnInit() {  
   console.log(this.myinputMsg);  
   }  
  
}  

In the above image, we have declared a variable( myInputMessage) shown in the selected area.

Now, let's open parent component views (app.component.html) pass this variable inside child component instance, which is passed inside parent component.

<div>  
<app-student [myinputMsg]="myInputMessage"></app-student>  
</div> 

The above image, represents 2 points.  Let's explain each of the points.

  1. Denotes those variables which will be used by child component (student component) with @Input decorator to fetch the message from parent component and,
  2. denotes those variables which are passed the parent component message to child component.

Now, open the child component's .ts file (student.component.ts) and import Input decorator, using the myinputMsg variable with @Input decorator and print it inside constructor or ngOnInit().

import { Component, Input, OnInit } from '@angular/core';  
  
@Component({  
   selector: 'app-student',  
   templateUrl: './student.component.html',  
   styleUrls: ['./student.component.css']  
})  
  
export class StudentComponent implements OnInit {  
@Input() myinputMsg:string;  
  
constructor() { }  
  
ngOnInit() {  
   console.log(this.myinputMsg);  
   }  
  
}  

** Output**

Output

In image 4, represent 3 points. Let's explain each of the points.

  1. First import the Input decorator, which is provided by angular and full path is @anuglar/core.
  2. Use @Input decorator and declare those variables which are passed by parent component Html(app.component.html) file's point 1.  When we declare those variable (myinputMsg) with @Input decorator it automatically fetches the value of the parent component variable with the help of @Input decorator.
  3. Print the values of this variable inside constructor or ngOnInit(). We have used inside ngOnInit().

Let's output,

@Output Decorator

@Output decorator is used to pass the data from child to parent component.  @Output decorator binds a property of a component, to send data from one component to the calling component.  @Output binds a property of the type of angular EventEmitter class.

To transfer the data from child to parent component, we use @Output decorator.

Lets's Open the child component' .ts file (student.component.ts).

For use the @Output decorator we have to import, two important decorators, they are Output and EventEmitter.

EventEmitter

Use in components with the @Output directive to emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance.

import { Component, Input, Output,EventEmitter, OnInit } from '@angular/core';  

Now, create any variable with @Output decorator.

@Output() myOutput:EventEmitter<string>= new EventEmitter();  

Here in the place of string, we can pass different types of DataTypes.

After that create a variable to store and pass the message to the parent component.

outputMessage:string="I am child component."  

Code

import { Component, Input, Output,EventEmitter, OnInit } from '@angular/core';  
  
@Component({  
   selector: 'app-student',  
   templateUrl: './student.component.html',  
   styleUrls: ['./student.component.css']  
})  
export class StudentComponent implements OnInit {  
   @Input() myinputMsg:string;  
   @Output() myOutput:EventEmitter<string>= new EventEmitter();  
   outputMessage:string="I am child component."  
   constructor() { }  
  
   ngOnInit() {  
      console.log(this.myinputMsg);  
   }  
}  

Send the value of output message, to the parent component.  Then we create a button and click on this button.  We will send the values to the parent component.

Let's open the child component Html page and create a button and click event of this button.  We then send the values.

student.component.html

<button (click)="sendValues"> Send Data </button>  

Now fire the click on student.component.ts.

sendValues(){  
   this.myOutput.emit(this.outputMessage);  
}  

Now, to fetch the value we have to go app.component.html file and use the below code.

<app-student [myinputMsg]="myInputMessage" (myOutput) ="GetChildData($event)"></app-student>  

function which is GetChildData() on parent component' .ts file, for fetch the data from child component.  
Open the app.component.ts:  
  
Code:  
  
GetChildData(data){  
   console.log(data);  
}  
Conclusion

In this article, we have learned how to pass data from parent to child component and vice versa, and which decorators are more responsible for doing this task, called @Input() and @Output() decorator.

I hope it will help you. Thanks!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Reactive form programming in Angular 7

Reactive form programming in Angular 7

In Angular, there are two ways to work with web forms: template driven forms and reactive forms. In template driven form, we use angular directives to build the internal representation of form in the html template file.

;Most of the code is written in html template file, making it sometimes difficult to understand and test.

Benefits

There are few benefits of using reactive form over the template forms. These are:

  • Add form controls more dynamically
  • Add form validation dynamically
  • Using custom validations

Reactive Form Programming

To start with reactive form programming, you should know about these classes:

  • Add form controls more dynamically
  • Add form validation dynamically
  • Using custom validations

Setting the project

ng new reactiveform> ng new reactiveform> ng new reactiveform### Add the ReactiveFormsModule in the Module file

In order to use Reactive Forms in your app, we have to first import ReactiveFormsModuleinapp.module.tsfrom@angular/forms, and then add in the @NgModule imports array.

app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

A Basic Control: FormControl

Let’s first create ourgeneralInfocomponent in the app.

ng new reactiveform
To create any form control, we first have to import FormControl from @angular/forms package into our component.

import { FormControl } from '@angular/forms';

After importing FormControl, we will create an instance of our form control firstName.

firstName = new FormControl('');

We can use the FormControl constructor to set the initial value of the control. Here, we are setting the empty string in the constructor.

Placing form control in template

After creating our first form control firstName in the controller file, it’s time to place this control in our html template file. Let’s put our form control in template.

general-info.component.html

<label>
FirstName : <input type="text" [formControl] = "firstName">
</label>

Using the template binding syntax, we bind our form control to the firstName input box in the template.

Displaying our component

In order to display our component in the browser window, we are going to place it in the app.component.html file.

app.component.html

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
 Welcome to {{ title }}!
 </h1>

 <app-general-info></app-general-info>


<router-outlet></router-outlet>

Notice line 7, we have placed our component <app-general-info></app-general-info> in this template. Now, let’s see how our form looks like in browser window.

Accessing Form Control Values

In reactive forms, you can access any form control state and value at any point of time. You can then manipulate the form control values from the component class or component template. Let’s see how to display our form control value in component template file.

Accessing form control value in template file

You can access and display the form control value using the value property.

general-info.component.html

<p>First Name: {{firstName.value}}</p>

The value on the form will change as you type in the form input control firstName.

As you can see in above screenshot, as we type zeptobook in our form control firstName, it is immediately displayed below.

Accessing and setting the form control value in component class

Like you access form control value in component template file, you can access it in component class programmatically. You can manipulate value here in component class file.

ng new reactiveform
Let’s see how to set the control value programmatically. In the general-info.component.ts file, we have a method updateFirstName(), and set the form control value ZeptoBook using this.firstName.setValue('ZeptoBook').

general-info.component.ts

updateFirstName(){
this.firstName.setValue('ZeptoBook');
&nbsp; }

general-info.component.html

Now, we have to write code to call this method from button click event. Let’s create a button and attach updateFirstName() method to button’s click event.

<p>
<button (click)="updateFirstName()">Update First Name</button>
</p>

Now, when user click on this button, it will set the form control value to ZeptoBook and update this in input box and label.

Setting initial value in form control

We can also set some initial value while creating the form control. Remember, we put empty string while creating our firstName form control. Now, let’s see how to use form control constructor to initialize the value in the form control.

general-info.component.ts

age = new FormControl(18);

Here, we have created an age form control and initialized its value to 18 in its constructor. Accessing the age form control in the component template file.

general-info.component.html

<label>
Age : <input type="text" [formControl] = "age">
</label>
<p>Age: {{age.value}}</p>

Now, open the browser and see the output.

Here you can see, Age input box and label is showing the initialized value of 18, which you can change anytime.

Now, let’s have a look at complete code.

general-info.component.ts

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


@Component({
selector: 'app-general-info',
 templateUrl: './general-info.component.html',
 styleUrls: ['./general-info.component.css']
})
export class GeneralInfoComponent implements OnInit {


constructor() { }


 ngOnInit() {}


firstName = new FormControl('');
age = new FormControl(18);


updateFirstName(){
 this.firstName.setValue('ZeptoBook');
 }
}

general-info.component.html

<p>
 Our General Info Component
</p>
<label>
 FirstName : <input type="text" [formControl] = "firstName">
</label>
<p>First Name: {{firstName.value}}</p>
<p>
 <button (click)="updateFirstName()">Update First Name</button>
</p>
<label>
 Age : <input type="text" [formControl] = "age">
</label>
<p>Age: {{age.value}}</p>

Grouping Form Controls: FormGroup

Above we read about basic form control, now let’s move forward to group of form controls called FormGroup. FormGroup is used to track the value and validation state of form control.

ng new reactiveform
Let’s create a new component app-form-group to demonstrate FormGroup.

ng generate component formGroup

Import FormGroup and FormControl

After generating our new component, it’s time to import these classes in component class.

form-group.component.ts

import { FormGroup, FormControl } from '@angular/forms';

Create FormGroup instance

Let’s create a property in our component class called sampleForm and set the property to a new Form Group instance. In the Form Group instance constructor, we have created these form control instances.

form control instances in form group

  • Add form controls more dynamically
  • Add form validation dynamically
  • Using custom validations

form-group.component.ts

sampleForm = new FormGroup({
   firstName: new FormControl(''),
   lastName: new FormControl(''),
   address: new FormControl(''),
   city: new FormControl('')
  });

Attaching FormGroup model with component view

Once we created sampleForm control in component class, it’s time to bind FormGroup model to our component view template.

Let’s see the syntax how to bind the model to view.

form-group.component.html

<form [formGroup] = "sampleForm" (ngSubmit)="onSubmit()">
 <label>First Name: <input type="text" formControlName="firstName"></label><br/>
 <label>Last Name: <input type="text" formControlName="lastName"></label><br/>
<label>Address: <input type="text" formControlName="address"></label><br/>
 <label>City: <input type="text" formControlName="city"></label><br/>
 <br/>
<button type="submit">Submit</button>
</form>

We have add a submit button, and add ngSubmit event. On pressing submit event, we are firing onSubmit() function of the component class. Let’s see the complete code.

form-group.component.ts

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


@Component({
 selector: 'app-form-group',
 templateUrl: './form-group.component.html',
styleUrls: ['./form-group.component.css']
})
export class FormGroupComponent implements OnInit {


 constructor() { }


 ngOnInit() {}


sampleForm = new FormGroup({
  firstName: new FormControl(''),
  lastName: new FormControl(''),
  address: new FormControl(''),
  city: new FormControl('')
 });


 onSubmit(){
   console.log(this.sampleForm.value);
  }
}

form-group.component.html

<p>
&nbsp; form-group works!
</p>
<form [formGroup] = "sampleForm" (ngSubmit)="onSubmit()">
  <label>First Name: <input type="text" formControlName="firstName"></label><br/>
  <label>Last Name: <input type="text" formControlName="lastName"></label><br/>
 <label>Address: <input type="text" formControlName="address"></label><br/>
 <label>City: <input type="text" formControlName="city"></label><br/>
 <br/>
  <button type="submit">Submit</button>
</form>

Also, in order to display this component in browser, I have commented our previous component app-general-info, and placed our app-form-group component. See the commented line 7.

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
 Welcome to {{ title }}!
 </h1>

 <!-- <app-general-info></app-general-info> -->
 <app-form-group></app-form-group>


<router-outlet></router-outlet>

Now, once you open your browser, and see the screen, it looks like this.

On submit, output will be rendered in browser console.window.

Now, see the red marked area in console log.

Easy way to generate Form Control: FormBuilder

When we have multiple forms, then it become very tedious and repetitive to create form controls. FormBuilder service is a easy way for generating form controls.

Let’s create a new component app-form-group to demonstrate FormGroup.

ng new reactiveform#### Import FormBuilder

After generating our new component, it’s time to import these FormBuilder in component class.

form-builder.component.ts

import { FormBuilder } from '@angular/forms';

Inject FormBuilder in Constructor

form-builder.component.ts

constructor(private fb: FormBuilder) { }

Creating the form controls

Here we are going to create a simple login form, having username and password form controls in component class.

builderForm = this.fb.group({
   userName: [''],
   password: ['']
 });

Now, notice the syntax, the declaration of FormGroup and FormControl are now implicit. This saves a lot of our code. We only need to have fields name with the default values.

Attaching FormBuilder model with component view

form-builder.component.html

<p>
 form-builder works!
</p>
<form [formGroup]="builderForm" (ngSubmit) = "login()">
<label>User Name: <input type="text" name="username" id="username" formControlName="userName"></label><br/>
<label>Password: <input type="password" name="password" id="password" formControlName="password"></label><br/>
<button type="submit">Submit</button>
</form>

If you see, we have a submit button, and attached login() function to this submit button. See the login() function in the component class file.

login(){
   console.log(this.builderForm.value);
  }

Add this component in app.component.html file

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
   Welcome to {{ title }}!
  </h1>

 <!-- <app-general-info></app-general-info> -->
 <!-- <app-form-group></app-form-group> -->
<app-form-builder></app-form-builder>


<router-outlet></router-outlet>

Open the browser, and see the result.

See the red marked console log. You can see the username and password fields values. The complete code is:

form-builder.component.ts

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


@Component({
 selector: 'app-form-builder',
 templateUrl: './form-builder.component.html',
 styleUrls: ['./form-builder.component.css']
})
export class FormBuilderComponent implements OnInit {


 constructor(private fb: FormBuilder) { }


 ngOnInit() {}


 builderForm = this.fb.group({
   userName: [''],
   password: ['']
 });


  login(){
   console.log(this.builderForm.value);
   }


}

form-builder.component.html

<p>
 form-builder works!
</p>
<form [formGroup]="builderForm" (ngSubmit) = "login()">
<label>User Name: <input type="text" name="username" id="username" formControlName="userName"></label><br/>
<label>Password: <input type="password" name="password" id="password" formControlName="password"></label><br/>
<button type="submit">Submit</button>
</form>

In this way, we created our simple form using the FormBuilder.

Summary

In this post, we learned about reactive form programming using the FormControl, FormGroup and FormBuilder. These are more powerful way of creating forms as compared to template driven approach. You can do lot of things in the component class file, making the component template file light and thin, containing only html syntax. This approach is also useful for testing purpose.

I hope you enjoyed more reading this blog.

Further reading:

The Pros and Cons of Angular Development

Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular

Angular 8 - Reactive Forms Validation Example

Angular vs React vs Vue: Which is the Best Choice for 2019?

A comparison between Angular and React

Getting Started with Nx in Angular

Learn Angular 8 from Scratch for Beginners

How to create a registration form using Angular 8 and Kendo UI

Top 15 Programming Languages by Popularity (2004-2019)

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 Tutorial - Learn Angular from Scratch

Angular Tutorial - Learn Angular from Scratch

Angular Tutorial - Learn Angular from Scratch: This course is for beginners who are curious on how to get started with Angular. In this course you will learn how to download, install and play around with Angular. We teach you the main components of Angular, so that you can get up and running with it asap. You will learn now to start building applications with Angular.

This course is for beginners who are curious on how to get started with Angular. In this course you will learn how to download, install and play around with Angular. We teach you the main components of Angular, so that you can get up and running with it asap. You will learn now to start building applications with Angular.

Learning Angular can be a daunting experience that's why this course was created; to give you an easier learning experience with it.

What am I going to get from this course?

  • You will learn the mayor fundamentals of Angular
  • You will learn how to get up and running with Angular
  • You will learn to create Applications using Angular 5 and beyond

What you'll learn

  • You will learn the mayor fundamentals of Angular
  • You will learn how to get up and running with Angular
  • You will learn to create Applications using Angular 5 and beyond