Are there better options than Angular timer, or is it still the top choice?

Currently, I am utilizing Angular 8 for a project where I have implemented a component that includes a checkbox to toggle the visibility of the footer.

Since the footer is a distinct component from the settings component, I find myself needing to use a setTimeout function to periodically check a local variable every 5 seconds in order to update the footer accordingly.

setTimeout(function(){ checklocalStorage() }, 5000);

While this approach works fine with just one timer, it becomes messy when multiple timers are involved. Is there a cleaner alternative to achieve this goal? Is constantly looping a timer to monitor changes in the localStorage variable the recommended practice?

Answer №1

Angular emphasizes the importance of component communication, and there are various approaches to achieve this within your team or project. In this particular case, using setTimeout is not recommended as it only triggers once and may not be efficient compared to setInterval which calls at repetitive intervals.

This means that if you interact with a checkbox, there could be a delay of almost 5 seconds before receiving feedback on the status change in the exposed or closed footer.

Instead, consider utilizing these four primary methods for binding data between components:

Services:

Create a service to facilitate communication between components. Services can be injected into multiple components, making them highly reusable across the application.

Simply create a Service and provide it in your module where necessary.

Create an Observable in the service and subscribe to it in components requiring access to the information.

Learn more about Observables at: https://angular.io/guide/observables

An example of Delayed Sequence in the provided link may align with your requirements.

NgRx:

Implementing Redux (NgRx) offers an advanced method for handling communication between components by ensuring immutable and reliable data management.

If not currently utilized, do not introduce NgRx solely for this purpose. By dispatching actions related to showing or hiding the footer, you can then subscribe to the stored data elsewhere.

Explore the store further here:

@Inputs and @Outputs:

For nested components, utilize Inputs and Outputs to transmit data between them. For instance, a "page" component containing the footer and checkbox could pass data up and down through bindings.

Exercise caution with this approach to ensure data integrity is maintained throughout the application.

Find additional information on Inputs, Outputs, and overall component interaction here: https://angular.io/guide/component-interaction

Event Bus:

An Event Bus could technically be employed to send notifications within the application, such as displaying the footer. However, this may not always be the optimal solution.

Event Bus functionality is typically suited for notification purposes when the origin of the action is less relevant than its occurrence.

Understand more about Event Emitters in Angular here: https://angular.io/api/core/EventEmitter

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

I'm new to NPM and Node.js and I'm currently exploring the differences between global and local dependencies installations, and how they are displayed in the package.json file

I'm primarily a designer who is diving into coding. Recently, I've been assisting with an Angular project at work and needed to learn how to utilize npm to install Angular CLI and its dependencies. Setting up my Angular project was a breeze. I m ...

Creating a unique type with a suffix of `px`

Understanding how to create a Position type class is clear: class Position { x: number = 0; y: number = 0; } However, I now require the x and y values to be integers with the suffix of px, like this: const position = { x: '1px', y: &ap ...

Error in Typescript/React: Unable to access the property 'MaxEmailLength' as it is undefined

I am facing an unusual problem with TypeScript. I have two static classes that are mutually referencing each other and causing issues. Class ValidationHelper (single file) import { ValidationErrors } from '../dictionary/ValidationErrors'; ex ...

Exporting enums within types in React Typescript

Here are the files I have: VehicleBrands.ts: export enum VehicleBrands { FORD = "ford", HONDA = "honda" } VehicleBrand.ts: import {VehicleBrands} from "./VehicleBrands"; export type VehicleBrand = VehicleBrands.FORD | V ...

Upgrading from Angular 2 to 4 causes compilation failure in project

Recently, I upgraded my Angular project from version 2 to version 4. The steps I followed for this upgrade are as follows: 1- Deleted the /node_modules/ folder 2- Executed the following command: npm install @angular/common@latest @angular/compiler@lat ...

Is there an issue with loading a local image? Could it be related to Angular or Chrome

Currently, I am working on a webpage that is designed to showcase a collection of images. The API I am using returns a list of objects, each containing an imgUri property which holds the absolute path to the corresponding image stored in a shared folder. ...

Building a comprehensive project using Prisma and Next.JS in TypeScript - encountering an issue where the props "Component" and "pageProps" are deemed invalid

I'm currently in the process of developing my very first full-stack application. In this project, I have chosen to use Next.js as my React framework and Prisma as my ORM for handling database access and migrations. Once I established the connection to ...

The subscribe method in Angular TS may be marked as deprecated, but worry not as it is still

I have developed a function that retrieves new data from a service file each time it is called. Here is how the function looks: onCarChange() { this.carService.getCarData(this.selectedCar).subscribe( async (response: CarData) => { if (response?.d ...

Troubleshooting: Custom HTML Attribute in Angular 8 Component HTML Not Functioning as Expected

I have a unique situation in my Angular 8 application where I utilize custom HTML attributes and then use jQuery to fetch those attributes for various styling purposes such as setting background images and adjusting the height of div elements. Below is th ...

What could be causing my TypeScript object to appear as "undefined" when I try to log it?

I created a StackBlitz demo featuring a button that, when clicked, should pass a value to the controller. In the controller, there is a function designed to assign this value to an object. However, TypeScript seems to be indicating that the object is undef ...

Angular2 Cascading Dropdowns

When using Angular2, I am interested in creating a cascading select for the array object provided with values of xs and ys: data:Array<Object> = [ {"x":50, "ys":[ 10, 15, 20, 25, 30, 35]}, ...

Enhance your material-ui component using TypeScript functionality

Exploring ways to enhance the Material-ui Button component by introducing new props. The objective is to introduce a new prop called fontSize with three size options - small, medium, large. <Button variant="outlined" color="primary" ...

Does this Spread Operator Usage Check Out?

Upon reviewing Angular's API documentation, I came across the declaration for the clone() method in HttpRequest as follows: clone(update: { headers?: HttpHeaders; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" ...

"Implementing marker clustering within Angular version 10 and above: A step-by-step

The code below draws inspiration from the official documentation and has been successfully implemented in my Angular 10 application: https://developers.google.com/maps/documentation/javascript/marker-clustering?hl=en import { AfterViewInit, ChangeDetection ...

Creating an interceptor to customize default repository methods in loopback4

Whenever I attempt to access the default repository code, I need to manipulate certain values before triggering the default crud function in the repository. How can I accomplish this? For example: ... @repository.getter('PersonRepository') priva ...

Automatically attaching a directive to every element having a specific class in Angular

Is there a way to dynamically add a directive to all elements within a component that have a specific class name? I am considering using document.getElementsByClassName("btn") I'm interested in applying the matRipple directive to any element with th ...

I have the capability to develop a library within Angular, but this is contingent upon the availability and integration of another native library from

Scenario: Dependencies: I am looking to develop a custom library for Angular 6. This library will include a service with functionalities to analyze strings, such as SQL syntax. Queries: Is it feasible to integrate [chevrotain] (https://github.com/SAP/c ...

I'm having trouble displaying my Angular project on Localhost:4200

I am facing an issue with my localhost:4200 where it is not displaying anything from my project. It was working fine before but after making some changes like generating a new component and modifying it, the page appears blank now.see image here see image ...

Discovering the process of iterating through values from multiple arrays of objects and applying them to a new response in Angular 8

Received the following data from an API response: const apiResponse = { "factoryId": "A_0421", "loss": [ { "lossType": "Planned Stoppage Time", "duration": ...

When the browser screen is minimized, the menu bar toggler in my Angular project stops functioning properly. I rely on Bootstrap features within Angular to handle this

When the browser is at full-screen mode, HTML works perfectly. However, when I resize the browser to a smaller size, the navbar disappears and a toggle is shown - which is the expected behavior. If I click on the toggle, the menu list should be displayed ...