Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon.

One key requirement is for each instance of this component to retain its own status.

For example, let's say we have three instances in the app.component.html:

<app-view-btn></app-view-btn>
<app-view-btn></app-view-btn>
<app-view-btn></app-view-btn>

Now, here is the code for the view-btn-component:

view-btn-component.html

<button>
    <i
        class="fa"
        [ngClass]="status ? 'fa-eye-slash' : 'fa-eye'"
        aria-hidden="true"
        (click)="clickEvent()">
    </i>
</button>

view-btn-component.ts

status: boolean = false;

  constructor() {}

  ngOnInit(): void {}

  clickEvent(){
    this.status = !this.status;       
  }

The current issue I am facing is that when the page reloads, the components lose track of their statuses.

Can anyone suggest how I can implement a solution where each component retains its status using local storage or any other method?

Answer №1

PLEASE NOTE: THERE IS ROOM FOR IMPROVEMENT IN THIS CODE BUT THE CORE IDEA REMAINS UNCHANGED!

Generate a unique input for each component to distinguish it:

<app-view-btn [name]="button0"></app-view-btn>
<app-view-btn [name]="button1"></app-view-btn>
<app-view-btn [name]="button2"></app-view-btn>

In your typescript file, you can implement something similar to the following. It is advisable to refine the code further, such as using JSON parsing techniques, but the concept remains the same.

@Input() name: string;
status: boolean = false;

  constructor() {}

  ngOnInit(): void {
// TODO: Enhance this section
const storageValue = localStorage.getItem(this.name)
    this.status = storageValue ? JSON.parse(storageValue) : false;
    }

  clickEvent(){
    this.status = !this.status;
// The status can be stored in an object if needed
    localStorage.setItem(this.name, JSON.stringify(this.status));
      }

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

Exploring Node Stream.Writable Extension in Typescript 4.8

I'm attempting to craft a basic class that implements Node stream.Writable, but it seems like I can't quite grasp the correct syntax - the compiler keeps throwing errors: https://i.stack.imgur.com/UT5Mt.png https://i.stack.imgur.com/Z81eX.png ...

Troubleshoot: Issue with binding data from DynamicComponentLoader in Angular 2 template

My implementation involves the utilization of DynamicComponentLoader and is based on the Angular2 API Guide. https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html The code structure I have set up looks like this: import {Page} fro ...

Tips for concealing information within the column labeled company Name with respect to the field designated as Company Name

I am currently working on an Angular 7 app and I am facing an issue: I cannot hide the data in the column for Company Name. The field "Name" in the report control JSON is labeled as Company Name. The report control is a table that contains various fields ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Oops! The system encountered a problem: the property 'modalStack' is not recognized on the type 'NgxSmartModalService'. Maybe you meant to use '_modalStack' instead?

Currently, I'm facing an issue while attempting to run ng build --prod in my Angular 6 project. I have also incorporated the NgxSmartModal package for handling modals. Unfortunately, the build process is failing and I can't seem to figure out why ...

Transferring data types to a component and then sending it to a factory

I have been grappling with creating a factory method using Angular 2 and TypeScript. However, my attempts have hit a roadblock as the TSC compiler keeps throwing an unexpected error: error TS1005: ',' expected. The issue arises when I try to pa ...

Angular SwitchMap is a powerful operator that allows you

I am currently utilizing the mat-table component from angular material, in conjunction with pagination features. Whenever a user inputs text into the search field, a filter method is activated to send the text, page size, and current page to the backend f ...

Exploring TypeScript Object Properties in Angular 2

How can I extract and display the ID and title of the Hero object below? The structure of the Hero interface is based on a Firebase JSON response. hero.component.ts import {Component, Input} from 'angular2/core'; import {Hero} from '../mod ...

Error message pops up in WebStorm when attempting to access the map object in Angular

Within one of the services in my Angular application, I have utilized the map() function to retrieve data from the GitHub API. getUser(username: string) { // Regular Expression used for String Manipulation return this.http.get('https://api.github.com ...

Stop images from constantly refreshing upon each change of state - React

Within my component, I have incorporated an image in the following way: <div className="margin-10 flex-row-center"> <span> <img src={spinner} className="spinner" /> ...

Only the (click) event is functional in Angular, while the (blur), (focus), and (focusout) events are not functioning

I have a unique HTML element as shown below <div (hover)="onHover()" (double-click)="onDoubleClick()" (resize)="resize()" (dragend)="dragEnd()"> These 4 functions are designed to display information onHover ...

Discovering the tab index of a tab header in Angular 4 Material

In my Angular application, I am using a mat-tab component to display tabs dynamically generated from an array. The template looks something like this: <mat-tab-group> <mat-tab *ngFor="let tb of dynTabs"> ...

How can you annotate and inherit a class method that returns an array of itself?

In the following example, I present a simplistic representation of code that may not align with standard HTML or front-end conventions. Please excuse any confusion this may cause. TL, DR I am facing challenges in specifying a return type for a method tha ...

What is the best way to ensure an observable has finished before retrieving a value?

Looking at the function provided below: public getAssemblyTree(id: number) { .... const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' })); request.sub ...

Tips for creating a unit test case in Angular 5 for API failures

Greetings! Currently, I am in the process of developing unit test cases for an Angular 5 application that involves utilizing APIs within the project. While I have successfully completed writing test cases for positive scenarios, I am facing challenges with ...

Steps for inserting a dropdown menu into a kendo grid

Hey there, I'm currently working on adding a drop-down list to a kendo-grid column but I'm facing an issue where the data is not loading into the drop-down list. My goal is to populate the data from an array. Here's the code snippet from t ...

How can two distinct sachems be returned in an http get request using res.json()?

There are two schemes that I have created: Sales and Abc I would like to send a response that includes the documents for both schemas: router.get('/', function(req, res) { Sales.find(function (err, sales) { if (err) return next(err) ...

Generate dynamic forms utilizing JSON data

I am in the process of developing an application that enables users to answer questions about themselves. The questions are being retrieved from an API. My next step is to generate a form with these questions as entry fields. I am currently utilizing a met ...

Exploring the Flow of Angular 5 HttpInterceptor

Implementing HttpInterceptor in one of my Angular applications to display a spinner for every request has been successful. However, I have encountered an issue with displaying an Error modal using a notificationService that utilizes SweetAlert. The code sn ...

Navigating the syntax of React with Typescript - Feeling lost

As I embark on my journey with Typescript/React, I find myself trying to decode the meanings behind it all. Coming from a C# background, this new environment presents a unique challenge for me. Despite going through several tutorials, I still find myself p ...