Execute code when there is a change in the object

Looking for a way to execute code whenever the active state changes? I keep track of the value like this:

export class AdminLayoutComponent implements OnInit, AfterViewInit {
activeState: string;
constructor(private router: UIRouter) {
    this.activeState = this.router.stateService.$current.name;
  }
}

Is there a method to run a code snippet (which assigns a class in the navigation menu for the active state) each time the current state is updated?

Answer №1

When multiple components are responsible for changing a "variable", the most efficient approach is to have the variable managed by a service. This way, in your component, you can:

get variable(){
    return myservice.variable
}
set variable(value){
    myservice.variable=value
    ...additional code when the variable changes... 
}
//Then, in your component, you can set
    variable="HelloWorld";
//Or in your .html file, you can display
     {{variable}}

Answer №2

Have you utilized the UI-Router library?

If so, it's likely that you'll need to incorporate the TransitionService hook into your code.

class MainComponent implements OnInit, AfterViewInit {
  currentActiveState: string;

  constructor(private routingService: UIRouter) {
    this.currentActiveState = this.routingService.stateService.$current.name;
  }

  ngOnInit(): void {
    this.routingService.transitionService.onSuccess({}, (transition: Transition) => {
      this.currentActiveState = this.routingService.stateService.$current.name;
      return true;
    }
  }
}

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

Create a custom data type that consists of a specific set of keys from an object

Is there a way to create a type in TypeScript that includes only a subset of keys from an object? Consider the example object below: const something = { cannary: "yellow", coyote: "brown", fox: "red", roses: "white", tulipan: "purple", palmera: ...

Remove Image Upload feature in antDesign and remove item from interface

I am currently working on a project that involves multiple interfaces. One of these interfaces is specifically designed for uploading images. However, I encountered a problem with the deletion icon functionality. Whenever the icon is clicked, a modal is su ...

The NullInjectorError has occurred due to the absence of a provider for the InjectionToken angularfire2.app

I am currently working on inserting form data into a Cloud Firestore database. Below is my x.component.ts file where I encountered an error in the constructor section: private firestore: AngularFireStore import { Component, OnInit } from '@angula ...

Importing and declaring child components in Angular testing with Karma, Jasmine, and TestBed is essential for comprehensive component testing. This ensures all

Challenge Description: When writing unit tests using karma/jasmine for an angular component that utilizes other angular components, there is a need to recursively import all components included in child components into the testbed configuration. Is there a ...

What is the reason behind TypeScript rejecting the syntax of checkbox input elements?

When trying to use the following checkbox in TypeScript, I encountered a warning: <input type="checkbox" onClick={(event: React.MouseEvent<HTMLInputElement>) => { setIsTOSAccepted(event.target.checked); }} defaultChecked={ ...

Connecting extra parameters to an event listener

Scenario: I am facing a situation where my event handler is already receiving one parameter (an error object). However, I now need to pass an additional parameter when binding the event handler. I am aware of the bind() method, but I am concerned that it ...

What is the process for running an Angular 1.4 application on a system with Angular 6 installed?

After installing Angular 6 with CLI, I realized that my project was written in Angular 1.4. How do I go about running it? ...

Transforming a TypeScript enum into an array of objects

My enum is defined in this structure: export enum GoalProgressMeasurements { Percentage = 1, Numeric_Target = 2, Completed_Tasks = 3, Average_Milestone_Progress = 4, Not_Measured = 5 } However, I want to transform it into an object ar ...

Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below: events: { load: () => { var chart : any = this; ...

Adding a blank line in an Angular table using primeNG to display database information requires a specific method

In my Angular application, I am utilizing primeNG table to display data fetched from a database. The table comes with 'add' and 'delete' buttons for user interaction. To view the interface, click on this link: https://i.stack.imgur.com/ ...

Sending JSON data from Angular to WCF

Attempting to utilize the post method in Angular to send JSON data to a WCF service. The data is being sent in JSON format from Angular, however, the WCF service is receiving it as a null object. Is it possible to use the get method to send JSON data? Th ...

receiving a null value in the JSON response

Preparing for the client to register. This function is responsible for registering a client. registerAsClient(){ this.loading =this.loadingCtrl.create({ content:"Setting up Account" }); this.loading.present(); this.buildClientData(); console.log( ...

Cypress - AG-Grid table: Typing command causing focus loss in Cell

Encountering a peculiar issue: I am attempting to input a value into the cell using 'type()'. My suspicion is that each letter typed causes the focus on the cell to be lost. It seems that due to this constant loss of focus and the 'type()& ...

Having trouble capturing emitted events from a child component in Angular 2+?

I have a question as a beginner. I'm trying to send a message from the child component to the parent component but for some reason, it's not working. app.component.html <app-cart-component> [items]="rootItems" (outputItems)=&quo ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

Event triggered before opening the cell editor in ag-Grid

I'm facing a scenario where I have a grid with rows. When a user double clicks on a cell, a cell editor opens up. There are events associated with the cellEditor - cellEditingStarted and cellEditingStopped, but I need an event that triggers just befor ...

Tips on customizing the selected icon color in Material-UI's BottomNavigationAction styling

I'm facing an issue with Material-UI styled components and could use some assistance. My goal is to create a BottomNavigation bar in React using Material-UI v5 where the selected option's icon displays in red (#f00) while the unselected icons sho ...

Utilizing React Router with the power of useCallback

My route configuration is set up as follows: const defineRoutes = (): React.ReactElement => ( <Switch> <Redirect exact from="/" to="/estimates" /> <Route exact path="/estimates" component={CostingPa ...

Universal NestJS GraphQL Guard

I am currently working on implementing a global guard to ensure that all requests receiving MUTATIONS from graphql require the token in their headers by default. The code below successfully achieves this: graphql-context-get-token.guard.ts import { ...

How can I use the target type (and maybe even the property type) as a type parameter within a decorator?

In the process of incorporating a deep-watch property decorator in Angular, the following usage has been implemented: @Component({ /* ... */ }) export class AppComp { @Watch( 'a.b.c', function (last, current, firstChange) { // ca ...