What is the best way to restrict the maximum number of items stored in local storage?

I'm creating a GitHub search app using the GitHub API in Angular. I want to restrict the number of items that can be stored in local storage. If the number of stored elements exceeds 5, the "Add to Favorite" button should either stop working or disappear. I attempted to achieve this with the following code snippet:

[ngStyle]="{'display': display.length > 5 && 'none' }"
, but it didn't produce the desired result. Here is the code:

HTML:

<input type="text" [(ngModel)]="profile" (ngModelChange)="detectChange($event)" (keyup)="findProfile()" class="input">

<ng-template [ngIf]="profile !== '' && user">
  <div class="profileContainer">
    <div class="leftDetails">
      <img class="userAvatar" [src]="user.avatar_url" alt="User Avatar">
      <div>
        <button class="button" [routerLink]="['', user.login.toLowerCase(), user.id ]">View Profile</button>
        <button class="button" [ngStyle]="{'display': display.length > 5 && 'none' }" (click)="addLocal()">Add to Favorite</button>
      </div>
    </div>

    <div class="rightDetails">
      <p><span>Username: </span> {{user.login}}</p>
      <p><span>Location:</span> {{user.location}}</p>
      <p><span>E-mail:</span> {{user.email}}</p>
      <p><span>Blog Link:</span> {{user.blog}}</p>
      <p><span>Member Since:</span> {{user.created_at}}</p>
    </div>

  </div>
</ng-template>

<div *ngIf="closeDiv">
  <div class="profileContainer" *ngFor="let item of display">
    <div class="leftDetails">
      <img class="userAvatar" [src]="item.avatar_url" alt="User Avatar">
      <div>
        <button class="button" [routerLink]="['', item.login.toLowerCase(), item.id ]">View Profile</button><br>
        <button class="button" (click)="removeLocal(item.id,item.storageKey)">Remove Favorite</button>
      </div>
    </div>

    <div class="rightDetails">
      <p><span>Username:</span> {{item.login}}</p>
      <p><span>Location:</span> {{item.location}}</p>
      <p><span>E-Mail:</span> {{item.email}}</p>
      <p><span>Blog Link:</span> {{item.blog}}</p>
      <p><span>Member Since:</span> {{item.created_at}}</p>
    </div>
  </div>
</div>

TypeScript:

import { HttpService } from '../http.service';
import { ProfileComponent } from './profile/profile.component';
import { JsonPipe } from '@angular/common';
import { bindCallback } from 'rxjs';
import { FormArray } from '@angular/forms';
import { ArrayType } from '@angular/compiler';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  user: any;
  profile: any;
  display: any;
  randomNumber: number;
  randomString: string;
  closeDiv: boolean = true;
  isClicked: boolean = true;

  constructor(private userData: HttpService) {}

  ngOnInit() {
    this.display = Object.values(localStorage).map((val: any) =>
      JSON.parse(val)
    );
    console.log(this.display);
  }

  public findProfile() {
    this.userData.updateProfile(this.profile);
    this.userData.getUser().subscribe((result) =>
      this.user = result;
    });
  }

  public addLocal() {
    this.randomNumber = Math.floor(Math.random() * 10000);
    this.randomString = this.randomNumber.toString();
    this.user.storageKey = this.randomString;
    localStorage.setItem(this.user.storageKey, JSON.stringify(this.user));
    this.display = Object.values(localStorage).map((val: any) =>
      JSON.parse(val)
     );
  }

  public removeLocal(id: any, key: string) {
    for (let i = 0; i < this.display.length; i++) {
      if (this.display[i].id === id) {
        this.display.splice(i, 1);
        localStorage.removeItem(key);
      }
    }
  }

  public detectChange(ev: any) {
    ev.length > 0 ? (this.closeDiv = false) : (this.closeDiv = true);
  }
}

Answer №1

Instead of using the map function with localStorage, I prefer to simply check the length of the localStorage and add a condition on the HTML or template side.

this.display = Object.values(localStorage).length;
<button class="button" *ngIf="display.length < 5">Add to           
Favorite</button>

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

Creating clones of <li> elements using JQuery and appending them to the end of a <ul> list

I have a regular ul li list and I am looking to add an additional li based on the first one in the list. Here is the HTML: <div id="gallery"> <ul> <li>Point Nr 1<p>lol</p></li> <li>Point Nr 2</li> <li> ...

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

Tips for creating an Angular component that can receive a single value from a choice of two different lists

My angular component requires a value that belongs to one of two lists. For example: @Input() public type!: enumA | enumB; However, this setup becomes problematic when the enums share values or are linked together in a way I find undesirable. I would pre ...

The TypeScript error arises when an element implicitly contains an 'any' type due to the inability to use an expression of type 'any' to index a specific type

Encountering an Issue: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ foo: string; bar: string; }'.ts(7053) Within the following code snippet: const CATEGORY_COLORS ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

Obtaining rotate3d values using JavaScript / jQuery

When dealing with an element that has a transformation like the following: style="transform: rotate3d(1, 0, 0, -50deg);" I am looking to extract the value -50 using Javascript or jQuery. It's essential for me to get the absolute value, so negative d ...

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...

Conceal Navigation with jQuery

Seeking assistance with jQuery for a new project. I'm trying to create a navigation menu that will automatically disappear after 3 seconds when a user enters the page. In its place, an arrow will be displayed instead of the original menu. Once the a ...

Decoding JSON on 9gag

I am trying to select a random image from the following URL: In order to display it correctly, I need to determine the size of the image. I am utilizing YQL to store the JSON result in a variable (referred to as source). After replacing 'https&apos ...

Discover the Category of Union based on Discriminator

Imagine a scenario where there is a concept of a union type called Thing, which combines types Foo, Bar, and Baz, each identified by the property tag. interface Foo { tag: 'Foo' foo: string } interface Bar { tag: 'Bar' bar: nu ...

Comprehending and interpreting a visible arrangement

I'm attempting to grasp the structure of observables and seeking guidance on locating the response, error, and complete sections. Additionally, I am curious about identifying the body and header parts in the response of a POST request. To gain insigh ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

How can I prevent the interpolation of "${variable}" in HTML when using AngularJS?

I need to display the string ${date} in a div element: <div>please substitute the ${date} as the tag for the name</div> The displayed content should be: please use the ${date} as the substitute tag to the name. However, the browser interpre ...

What is the best way to create fading text effects in an AngularJS application?

Running an AngularJS web application that showcases three words for 5 seconds each: Hello, World & Goodbye. The controller setup is as follows: self.currentIndex = 0; self.myTexts = ['Hello', 'World', 'Goodbye']; self.cu ...

Changing the route variable in React Native's bottom bar tab functionality

https://i.sstatic.net/ESGur.png I am looking to create a consistent bottom tab bar that remains the same on every screen, but I want the routes of the tabs at the bottom to change dynamically. For example, in Screen1, the tab at the bottom should route to ...

ng-model causing simultaneous changes to all selects

Check out this jsfiddle link Hello there, I'm encountering an issue with my application. I need to create multiple dropdowns using ng-repeat and have them all populated with the same options. The problem arises when one dropdown is changed, all ot ...

"Looking to log in with NextAuth's Google Login but can't find the Client Secret

I am attempting to create a login feature using Next Auth. All the necessary access data has been provided in a .env.local file. Below are the details: GOOGLE_CLIENT_ID=[this information should remain private].apps.googleusercontent.com GOOGLE_CLIENT_SECR ...

Combining JSON objects in a Pentaho JavaScript JSON by matching keys to merge with an existing JSON document

My goal is to construct a Json document by breaking it down into smaller pieces, with each piece containing the necessary keys to insert the smaller Json bits into the correct json structure. As I am relatively new to JavaScript and still in the process of ...

What causes the variable assigned in the outer subscription's scope to change as the inner subscriptions change?

In my Angular 6 code snippet provided below, I am facing an issue: ngOnInit() { this.route.queryParams.subscribe((params: Params) => { const stuffId: string = params.stuffId; this.service.getState().subscribe((state) => { ...

Angular 2: Applying a class to a specific element by referencing its id

I am trying to figure out how to add a class to an element with a specific id in Angular 2. In regular JavaScript, you can do it like this, but I need help translating this into Angular 2: document.getElementById("MyElement").className += " active"; Cur ...