Is it possible to utilize the Angular selector twice while only initializing the component once?

HTML

 <exchange></exchange>
 <exchange></exchange>

TS

        @Component({
          selector: 'exchange',
          templateUrl: 'exchange.component.html',

        })
        export class ExchangeComponent implements OnInit {
           ngOnInit() {
              interval(10000).subscribe(x => {
              console.log(x)});
           }
        }

In this scenario, the component is called twice but I only want the interval to run once every 10 seconds instead of twice. How can I achieve this without triggering the interval multiple times?

Answer №1

Perhaps consider a straightforward solution like the following:

Create a variable in a service file that triggers an action based on its value.

shouldSubscribe: boolean = false;

In your component.ts:

ngOnInit() {
 if(!this.someService.shouldSubscribe) {
    interval(10000).subscribe(x => {console.log(x)});
 } else {
    this.someService.shouldSubscribe = true;
 }     
}

An alternate method is to pass a property to specific instances of your component and use it as a condition:

<exchange [shouldSubscribe]="true"></exchange>
<exchange></exchange>

In component.ts:

@Input() shouldSubscribe: boolean;

And within the lifecycle hook:

if(this.shouldSubscribe) {
// do what is needed
} 

Your query mentioned preventing the component from reinitializing, which cannot be avoided (By skipping ngOnInit, it will still execute due to being a lifecycle hook).

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

Attempting to integrate Bootstrap 5 accordion into Angular 17 using ngFor has posed a challenge for me

<div class="accordion w-50 mx-auto" id="accordionExample"> <div *ngFor="let note of notes; index as i;"> <div class="accordion-item"> <h2 class="accordion-header" id="headi ...

Is having only one FCM token sufficient for storing data from multiple devices?

I'm currently working on an Angular website and looking to send push notifications to users subscribed on both desktop and mobile. I am utilizing Firebase Cloud Messaging for this purpose and wondering if storing a single FCM token will suffice for se ...

Trying out cellRenderer in Angular's Ag Grid with Jest to validate values

I am facing an issue where I need to test the actual values displayed in a column of an Ag Grid table. These values are formatted using a cellRenderer based on specific conditions. In my Jest test, I have experimented with various approaches: Using fixtu ...

Utilizing TypeScript for parameter typing in React Router's URLs

When trying to type URL parameters, I encountered an error stating "type {} is missing the following properties from type RouteComponentsProps<MatchParam,StaticContextn unkwon>: history, location, match. How do I correctly type URL parameters in Type ...

Glitch causing incorrect images to appear while scrolling through FlashList

Currently, I am using the FlashList to showcase a list of items (avatars and titles). However, as I scroll through the list, incorrect images for the items are being displayed in a mixed-up manner. Based on the explanation provided in the documentation, t ...

Submitting the object in the correct format for the Firebase database

My goal is to structure the Firebase database in the following way: "thumbnails": { "72": "http://url.to.72px.thumbnail", "144": "http://url.to.144px.thumbnail" } However, I am struggling to correctly set the keys '72' and '144&apos ...

Unable to connect with API data in Angular 6

I have been using an API to retrieve data and display it on a webpage. While I am able to see the response in the console, I am facing difficulty binding the data to the user interface. Nothing is appearing on the screen as expected. This is my HTML code: ...

What could be the reason for TypeScript inferring the generic type as an empty string?

I have developed a React component known as StateWithValidation. import { useStateWithValidation } from "./useStateWithValidation"; export const StateWithValidation = () => { const [username, setUserName, isValid] = useStateWithValidation( ( ...

Issue with triggering Observable during an Angular 2 HTTP call

In my current setup using Ionic 2 with Angular 2, I have the following method implementation: private login(params: any, url: string){ var p = new Promise<JsonResult>((resolve, reject) => { let body = JSON.stringify(params); l ...

I encountered TS2300 error stating a duplicate identifier appeared once I transferred my code to Angular CLI

Currently undergoing the process of transitioning our code to Angular CLI for our hybrid app. The plan is to migrate the Angular part to CLI while the AngularJS portion continues to be handled by custom Webpack. It's worth noting that both parts (Angu ...

Is there a way to delegate properties in Angular 2+ similar to React?

When working with React, I have found it convenient to pass props down dynamically using the spread operator: function SomeComponent(props) { const {takeOutProp, ...restOfProps} = props; return <div {...restOfProps}/>; } Now, I am curious how I ...

Transforming an array of JavaScript objects into arrays of key-value pairs based on a specific property with ES6 syntax

Consider an array of objects like this: myArray = [ {name: 'First', parent: 1, delta: 2}, {name: 'Second', parent: 1, delta: 1}, {name: 'Third', parent: 2, delta: 1} ]; The goal is to transform this array into an objec ...

"Angular throws an error code NG5002 when encountering an invalid ICU message along with an unexpected

Currently, I'm utilizing the most recent release of Angular 17.0.0-next.6, which introduces support for the updated control flow. Interestingly, individuals on Twitter have mentioned that it works flawlessly for them; hence, the issue likely resides w ...

What is the best approach for arranging numbers in descending order?

I'm struggling to sort numbers from largest to smallest and need some help. My code successfully sorted numbers with 5 digits, but not the others. Here is a snippet of the unsorted numbers: 15366 13070 13069 13068 13067 13 ...

`Two side-by-side nvd3 visualizations`

I am seeking assistance with arranging two nvd3 graphs side by side on a webpage. Below is the code I am currently using: <div class="container" > <!-- Graph 1--> <div class="rows"> <nvd3 [options]="optionsGraph1" [data]="Gra ...

Challenge with Google Maps Data Layer

I am currently facing challenges with implementing the Google Maps React API and navigating through the Google Maps documentation. My goal is to display a polygon on the map and perform various manipulations. Here's what I have accomplished so far. I ...

Cannot upload the same file to both Spring and Angular twice

Having trouble uploading the same file twice. However, it works fine when uploading different files. Encountering an error under the Network tab in Chrome { timeStamp: ......, status: 417 error: 'Bad Request', message: 'Required reques ...

Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string. I tried following an example in the Hero Angular App, bu ...

Angular2 - Leveraging data to dynamically control radio buttons

I am looking to implement radio buttons in a form using Angular 2 with a data-driven approach. In my component, I have set up a form as follows: import { Component } from '@angular/core'; import {FormControl, FormGroup, Validators} from '@a ...

Issue encountered with combineLatest following upgrade of rxjs from version 6.x to 7.x

Upon upgrading rxjs from version 6.6.6 to 7.4.0, an error surfaced in my combineLatest function. searchQuery = new FormControl(null); searchStatus = new FormControl<UserStatus>('ALL'); searchParams$ = combineLatest( this.searchQuery.valu ...