Ways to Prompt a User to Select the "Remember Me" Option

How can I implement the functionality of 'Remember Me' on a login page? I want users who click on 'Remember Me' to be able to reopen the page without logging in again, even after closing their browser. But how do I differentiate between users who clicked 'Remember Me' and those who did not?

HTML

<form  (ngSubmit)="onSubmit(form.value)" #form="ngForm">
  <ng-content select='h3'></ng-content>
    <label> 
    Email Address
    <input type="email" name="email">
  </label>

    <label> 
    Password
    <input type="password" name="password">
  </label>
     <label style="display: flex">
    <input type="checkbox"> 
    Remember me.
  </label>
<button type="submit">Login</button>
</form>

Component

    ngOnInit() {
     this.AutoLogin();
    }

    onSubmit() {
    this.auth.login(this.loginForm.value).subscribe((res) => {
      localStorage.setItem('token', res['accessToken']);
      localStorage.setItem('name', res['name']);
      localStorage.setItem('role', res['role']);
      localStorage.setItem('email', res['email']);
      localStorage.setItem('userId', res['userId']);
      this.toastrService.success('Successfully Login!');
      this.router.navigate(['/home']);
    },
    (err) => {

    });
  }

    AutoLogin(){
        var accessTokenObj = localStorage.getItem("token");
    console.log(accessTokenObj);
        if (accessTokenObj) {
          this.router.navigate(['/home']);
        } else {
          console.log("You need to login")
        }
       }

Answer №1

You can improve the user experience by storing the "remember me" value in a model and saving it to local storage, then checking in the autoLogin() function.

HTML

<form  (ngSubmit)="onSubmit(form.value)" #form="ngForm">
  <ng-content select='h3'></ng-content>
    <label> 
    Email Address
    <input type="email" name="email">
  </label>

    <label> 
    Password
    <input type="password" name="password">
  </label>
     <label style="display: flex">
    <input type="checkbox" [(ngModel)]="rememberMe"> 
    Remember me.
   </label>
  <button type="submit">Login</button>
 </form>

Component

rememberMe: boolean;
ngOnInit() {
     this.rememberMe = false;
     this.AutoLogin();
    }

    onSubmit() {
    this.auth.login(this.loginForm.value).subscribe((res) => {
      localStorage.setItem('token', res['accessToken']);
      localStorage.setItem('name', res['name']);
      localStorage.setItem('role', res['role']);
      localStorage.setItem('email', res['email']);
      localStorage.setItem('userId', res['userId']);
      // Save value to local storage
      if(rememberMe) {
        localStorage.setItem('rememberMe', 'yes')
      }
      this.toastrService.success('Successfully Login!');
      this.router.navigate(['/home']);
    },
    (err) => {

    });
  }

    AutoLogin(){
        const accessTokenObj = localStorage.getItem("token");
        // Retrieve rememberMe value from local storage
        const rememberMe = localStorage.getItem('rememberMe');
    console.log(accessTokenObj);
        if (accessTokenObj && rememberMe == 'yes') {
          this.router.navigate(['/home']);
        } else {
          console.log("You need to login")
        }
       }

I trust this information will be beneficial to you.

Answer №2

When it comes to the concept of "remember me," there are different ways to implement it depending on whether you are looking at auto-login on the client side or storing data on the server for authentication purposes. For auto-login functionality, you can refer to this resource: . On the other hand, if you need to remember users during authentication and store specific data on the server, check out the guidance provided by Laravel here: https://laravel.com/docs/6.x/authentication#remembering-users

Answer №3

Here is a simpler way to handle this:

if(rememberMe){
  sessionStorage.setItem("token", MY_TOKEN);
}else{
  localStorage.setItem("token", MY_TOKEN);
}

Next step, set up an Authentication RouteGuard.

@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(public router: Router) {}
  canActivate(): boolean {
    var token = sessionStorage.getItem("token") || localStorage.getItem("token");
    if (!isAuthenticated(token)) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for setting up SSL for Angular e2e testing?

I'm working on an Angular sample project that includes end-to-end tests focusing on OAuth2 and OIDC flows. I've noticed that the behavior of browsers varies when SSL/TLS is enabled or disabled. To ensure consistency, I would like to run my end-to ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

What is the proper method for typing unidentified exports that are to be used in TypeScript through named imports?

Currently, I am developing an NPM package that takes the process.env, transforms it, and then exports the transformed environment for easier usage. The module is structured like this: const transformedEnv = transform(process.env) module.exports = transf ...

Exporting third party definitions from a TypeScript npm module for reuse in other projects

Our custom npm logging module, which is built using TypeScript and relies on the pino library, encounters errors when being imported into an application: Error: node_modules/@scope/logging/lib/index.d.ts(1,23): error TS2688: 'pino' type definiti ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Angular 4 prohibits certain special characters and the number zero

Currently, I am a beginner in Angular 4 and I am working on learning how to search for data from a text box. However, whenever I input special characters like "%" in my code, it triggers an error leading to a crash in my application. Is there any effectiv ...

Choose several checkboxes from the dropdown menu

After clicking the dropdown, I want to select multiple checkboxes instead of just one. I have tried using the prevent default method but it did not work. Beginner concept ...

Looking to start using WebDriverIO and Typescript with the WDIO wizard? Here's how to get it

I'm in the process of setting up a WebdriverIO project using TypeScript and Cucumber. I followed the steps provided by the wizard, which was pretty straightforward. I opted for Cucumber, TypeScript, and the page object model. This setup created a tes ...

'The signatures of each of these values are not compatible with one another.' This error occurs when using find() on a value that has two different array types

Here's the code snippet I'm attempting to run within a TypeScript editor: type ABC = { title: string } type DEF = { name: string } type XYZ = { desc: ABC[] | DEF[] } const container: XYZ = { desc: [{title: & ...

Show images from an array of base64 image data

I am currently facing an issue while trying to display images in base64 format within a RadListView component. Within the loop of the component, I have the following code snippet: let base64ImageSource = new ImageSource; base64ImageSource = fromBase64(re ...

Using TypeScript to create a unique object type that is mapped with generics for each key

Suppose I have a type representing an array of two items: a list of parameters and a function with arguments corresponding to the parameters. I've created a handy function to infer the generic type for easy use. type MapParamsToFunction<A extends a ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

ng2-select2 prevent selection of initial value

My Angular project has the following setup: Hello.component.html <select2 ngDefaultControl [data]="list" [options]="{ placeholder: placeholder }" > </select2> Hello.component.ts list = [ { id: 1, text: 'Item 1 one' }, { i ...

When compiling TypeScript, the exported module cannot be located

I've encountered an issue while working on my TypeScript project. Upon compiling my code with the following configuration: { "compilerOptions": { "target": "ESNext", "module": "ESNext", & ...

How can you implement multiple validators on a single control in Angular 2?

I've been working on a form using Angular2 and I've implemented two custom validators for the email address field. The initial validator checks for valid email format, while the second (which is asynchronous) checks if the email address already ...

Deactivate the rows within an Office UI Fabric React DetailsList

I've been attempting to selectively disable mouse click events on specific rows within an OUIF DetailsList, but I'm facing some challenges. I initially tried overriding the onRenderRow function and setting CheckboxVisibility to none, but the row ...

Icon appearing outside the button instead of inside

Here's a button I'm working with: <button class="glyphicon glyphicon-option-horizontal" (click)="myFuncion()"></button> Recently, I updated my bootstrap library from version 3 to 4.2.1 and now the icon is no longer visible. I' ...