2

i have an object named model i want it to store in localstorage .

model.username and model.password are two fields of my form. i want to store model.username in local storage. i need to add every username to be added in local storage. But in my case every time i tried entering new username the previous username get overwritten in local storage i.e. only one username is only stored in ls anytime.

Following is the login template

<form  (ngSubmit)="f.valid && onSubmit(f) " #f="ngForm" novalidate>
  <div>
  <label for="username">Username</label>
          <input type="text"  name="username" [(ngModel)]="model.username" #username="ngModel" required appForbiddenName="jimit" />
          <div *ngIf="f.submitted && !username.valid" >Username is required</div>
          <div *ngIf="username.errors.forbiddenName">
            Username has already taken.
          </div>

  </div>
  <div>
    <label for="password">Password</label>
          <input type="password"  name="password" [(ngModel)]="model.password" #password="ngModel" required />
          <div *ngIf="f.submitted && !password.valid">Password is required</div>
  </div>      
  <div>    
         <button type="submit" >Login</button></div>

  <div>
    <button type="reset">Clear</button>
  </div>

  </form>

  <button (click)="onRegister()">Register</button>

Following is the login component

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

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

  constructor(private router: Router) {
    }

 model: any = {};

onSubmit(form: NgForm) {

  console.log(form.value.username);
  console.log(this.model.username);
  localStorage.setItem ('username', this.model.username);
  this.router.navigate(['/home']);
}

onRegister() {
  this.router.navigate(['/register']);
  window.alert('please wait while we process your request');
}


  ngOnInit() {
  }
stack overflow
  • 3,135
  • 2
  • 6
  • 7

2 Answers2

2

Ignoring the strange idea of storing multiple usernames in localStorage, you can do this by inserting an array or object. Because the keys of localStorage are unique:

const usernames = JSON.parse(localStorage.getItem('usernames') || '[]');

if (!usernames.includes(this.model.username)) {
  usernames.push(this.model.username);
  localStorage.setItem('usernames', JSON.stringify(usernames));
}

If however you are doing this to get the data later after navigating, I suggest you have a thorough read about using services/store instead of localStorage.

Poul Kruijt
  • 64,681
  • 11
  • 135
  • 134
-1

local storage store the value based on key and hold only one value at a time not hold an array.