The components are not syncing with each other, causing discrepancies in their values. Synchronization is crucial for maintaining consistency throughout the system

How can I ensure that two instances of the same component on a page are always synchronized, so when one changes, the other also changes simultaneously? Currently, only one component updates when a button is clicked. How can I make them change together and always stay similar or identical?

page.component.html

<app-clock></app-clock> //same component 
<app-clock></app-clock> //same component

clock.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { SiblingService } from '../sibling.service';

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

  public clockIn: any[]= [];
  public clockOut: any[]= [];
  public tCount: any[]= [];
  today = Date.now();
  public enableButton = false
  constructor(public datepipe: DatePipe, private sibService: SiblingService) {

    setInterval(()=> {this.today = Date.now()},1)}

  ngOnInit(){}

  public regClock(){


    let currentDT = this.datepipe.transform((new Date), 'MM/dd/yyyy h:mm');
    let check = true;

    if (this.enableButton == true){
      this.enableButton = !this.enableButton;
      this.clockOut.push(currentDT);
      let lastC_in = this.clockIn[this.clockIn.length-1];
      let lastC_out = this.clockOut[this.clockOut.length-1];
      let start = new Date(lastC_in).getTime();
      let end = new Date(lastC_out).getTime();
      let time = end - start;
      let diffDay = Math.floor(time/86400000);
      let diffHour = Math.floor((time % 86400000)/3600000);
      let diffMin = Math.floor(((time % 86400000)%3600000)/60000);
      let timeCount = diffDay + "day(s) "+ diffHour+"Hour(s) "+diffMin+"Min(s)"
      this.tCount.push(timeCount);
    
    }
    else{
      // console.log("in")
      this.clockIn.push(currentDT);
      this.enableButton = !this.enableButton;
      
    }


  }

}

clock.component.html

<div class="outer">
    <div class="inner">
     <div class="time" id="f-way"> {{today | date: 'fullDate'}}</div>
     <div class="time" id="t-way"> {{today | date: 'h:mm:ss a'}}</div>
    </div>
    <div [ngSwitch]="enableButton" id="btn-p">
        <button *ngSwitchCase="false" (click)="regClock()" class="btn" >Clock In</button>
        <button *ngSwitchCase="true" (click)="regClock()" class="btn" >Clock Out</button>
    </div>
</div>

Answer №1

Both components are rendered in the DOM every time they are called, creating separate instances. This means changes made in one component will not automatically be reflected in another.

To have changes in one component reflected in another, you can create a global service that is shared among your components. Any changes made in one component should update the value in the global service, allowing it to be reflected in the other instance of the same component (by subscribing to it).

I recommend exploring Subjects and Services for sharing data to achieve the desired outcome.

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

Is it possible to export all types/interfaces from .d.ts files within multiple folders using index.ts in a React TypeScript project?

In my current React project, I am managing multiple configuration folders: -config -api/ |index.ts |types.d.ts -routes/ |index.ts |types.d.ts ... For example, in the api/index.ts file, I can import necessary types using import {SomeTyp ...

Creating a new line in the content of a MatDialog in Angular 7

I have a situation where I am using MatDialog and attempting to insert a new line in the content definition. I've tried using both \n and </b>, but neither of them seem to work. Is there an alternative way to achieve this without manually e ...

What could be causing the lack of change detection triggering in nested dynamic components?

I'm encountering an issue with change detection in a nested dynamic component that involves content projection. For some reason, the child component is not being automatically triggered for change detection, necessitating manual intervention for every ...

Issues encountered while establishing a connection to an API in React Native

When attempting to log in a user by connecting to my API, I encountered some issues. It seems that every time my laptop has a different IP address, I need to make changes in the file where the fetch or XMLHttpRequest is located in order for the login proce ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

Is it possible to substitute an Angular component with a component from a custom module in a similar fashion to utilizing a decorator in AngularJS?

I am currently working on an application that caters to a diverse customer base. Each customer has unique customization needs for their user interface. We are interested in replacing certain components with customer-specific ones, but have been facing chal ...

What is the best way to go back in Angular 5 - using href or location.back()?

I recently encountered a dilemma with my app where users navigate to a dead-end page without any way to return. Picture clicking on a program in a TV guide and getting stuck on that program's details page, not being able to go back to the main guide. ...

How can we effectively make a call to another API using the Refresh Token within an Angular Interceptor?

I needed to refresh the access token before sending an API request. The new token will be added to the previous API call within the interceptor. How can I trigger another API call in an Angular interceptor? import { Injectable } from '@angular/core&ap ...

Encountering a TypeScript error when trying to establish a connection to MariaDB using node

working with mariadb npmjs version: 2.1.2 import mariadb from "mariadb"; const pool = mariadb.createPool({host: process.env.DBHOST, user: process.env.DBUSER, password: process.env.DBPASS, port: process.env.DBPORT, connectionLimit: process.env.DBCONNLIMIT, ...

Angular - Using HttpClient for handling POST requests

The example provided in the official Angular HttpClient documentation demonstrates how to make a POST request to a backend server. /** POST: add a new hero to the database */ addHero (hero: Hero): Observable<Hero> { return this.http.post<Hero&g ...

What steps are involved in developing a responsive sidenav bar utilizing angular material exclusively?

Is it possible to achieve a similar functionality to the sidenav example created with mdbootstrap using Angular materials 4? The example can be found here: link to responsive sidenav with buttons and lists. I prefer not to use bootstrap 4 because it requi ...

"Elaborate" Typescript Conditional Generic Types

Scenario I am currently working on implementing strong typing for the onChange function of a UI library's Select component. To provide some context, the existing type definition for their onChange is as follows: onChange?: (...args: any[]) => v ...

Error: nvm command not found

I downloaded nvm for windows and successfully installed two versions of nodes by following the steps provided in this article. https://medium.com/appseed-io/how-to-run-multiple-versions-of-node-js-with-nvm-for-windows-ffbe5c7a2b47 The node versions I hav ...

Is there a way to seamlessly transfer (optional) parameters from a CloudFormation template to a CDK resource within a CfnInclude without statically defining the list of parameters?

Trying to grasp these syntax rules, unsure if it's possible. We have numerous CloudFormation templates that we want to deploy using CDK by constructing them with CfnInclude. The issue is that CfnInclude always needs an explicit parameters argument if ...

Explore Angular's ability to transform a nested observable object into a different object

My task involves mapping a field from a sub object in the response JSON to the parent object The response I receive looks like this: { "id": 1, "name": "file-1", "survey": { "identifier": 1, "displayedValue": survey-1 } } I am attempting ...

Java Spark API using basic authentication will issue a 401 error response when accessed from an Angular application

My Java Spark API is set up for basic authentication. When I make a call to the URL from Postman with basic auth, it returns a JSON response. However, when I make the same call from an Angular 4 application, I get the error message: "Response for preflight ...

Footer Cell isn't showing up as expected within *ngFor loop in Mat-Table

I'm having trouble displaying the total sum at the bottom of my table. Despite following the steps outlined in the documentation exactly, it still doesn't seem to be working for me. Below you can find the code from my template: <table mat-t ...

Refreshing list after deleting an item in Angular 4

As I develop a website for upcoming concert events, I faced an issue where deleting an event from the backend (Ruby on Rails) did not trigger a front-end refresh. The new event creation works perfectly fine by saving it to the database and immediately disp ...

Believed I had a clear understanding of the situation

Within the following code snippet, I am utilizing a service (Angular) to extract text using a fileReader and implementing a promise for the asynchronous part. However, I am encountering an issue that appears to be related to scope, which is causing confusi ...

Retrieve user information by their unique user ID from a MongoDB database using a Node, Express, and TypeScript API

Currently, I am working on a Node JS and Express with TypeScript API project. In this project, I need to retrieve data stored by a specific user from MongoDB based on their user ID. This is a snippet from my DataRouter.ts: router.get('/:userId', ...