`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look.

For example:
If the headerStyle member of the service is set to dark, the dark header theme is applied for that specific route. If it is set to light, then the light theme takes over, and so forth.

The issue I encounter is when transitioning from 'route1' to 'route2', I must manually reset the service member for 'route2'. This becomes cumbersome as the new styles are only applicable to 2-3 pages, yet I still need to call the service on every page. Failure to do so means the values in the service remain unchanged, retaining the style from the previous route.

What I aim to achieve is this: once the route begins to change, all UI service styles should reset to default. Then, upon completion of the route change, if the new page has different values for the UI service, those should be applied; otherwise, render the page using default styles.

A similar question has been raised here:
How to detect a route change in Angular 2?

The challenge lies in the fact that the route change event fires after the transition is complete, ultimately overriding any code present on the page with default settings!

Answer №1

By subscribing to events, it is possible to monitor various navigation occurrences. Detailed information can be found in the API documentation. One important event to note is NavigationStart. Another approach is to include the Router service in your StyleService and subscribe to events from there:

@Injectable()
export class StyleService{
    constructor(private router: Router){
        router.events.subscribe((val) => {
            if (val instanceof NavigationStart) {
                this.resetStyle();
            }

            if (val instanceof NavigationEnd) {
                this.setStyle(router.routerState);
            }
        });
    }
}

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

How can I ensure that Chakra UI MenuList items are always visible on the screen?

Currently, I am utilizing Chakra UI to design a menu and here is what I have so far: <Menu> <MenuButton>hover over this</MenuButton> <MenuList> <Flex>To show/hide this</Flex> </MenuList> </ ...

Make your CSS and JS files smaller by using a PHP compression script in your WordPress child theme

  I am looking to implement a PHP script that will serve combined, pre-gzipped, and minified JS and CSS files. You can find the source code for this script here: https://code.google.com/p/compress/ I have a WAMP localhost with WordPress install ...

When utilizing jQuery in HTML, the Marquee will bounce back upon reaching the end

My issue is that when I use a regular marquee, the text simply goes to the end and does not bounce back to the start as soon as it reaches the end of the div. Instead of using a normal marquee, I am looking to achieve this desired effect by utilizing jQue ...

TypeScript Add Extract Kind

I am currently working on implementing a function called sumPluck. This function will allow the user to specify a property of type number from an object in an array, and then calculate the sum of all those properties. For example: type A = { prop: number ...

When attempting to validate dates with the after: rule in vee-validate while also utilizing a computed field in Vue.js, the validation process may encounter unexpected issues

Below is a codepen with a simple input field for entering dates: <input type="text" v-model="startDate" name="StartDate" v-validate="{ required: false, date_format: 'dd/MM/yyyy', before: maxStartDate }"/> Despite e ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Utilizing the Bing Translation API to translate an entire webpage

I am currently attempting to use the Bing API to translate an entire webpage instead of using the Bing widget. This is because I want to create a custom design for the translation panel, However, I have been unable to find any resources on how to do this ...

What steps should be taken to enable SCSS in Jest for unit testing in TypeScript Next.js?

I am facing an issue with the scss import in my project. I have attempted to solve it by using mockup and identity-obj-proxy, but neither of them seems to work. I suspect that there might be a problem with my regex expression. The specific error arises fr ...

Learn how to display separate paragraphs upon clicking a specific item

New to coding and eager to learn, I have recently started exploring HTML, CSS, and basic JavaScript. In my journey to enhance my skills, I am working on building a website for practice. One particular page of the site showcases various articles, each acc ...

Tips for preventing the ngbTypeahead input field from automatically opening when focused until all data is fully mapped

When clicking on the input field, I want the typeahead feature to display the first 5 results. I have created a solution based on the ngbTypeahead documentation. app.component.html <div class="form-group g-0 mb-3"> <input id="typ ...

Encountering a Node.js error when executing the JavaScript file

When I try to run my Node.js application using the command "node main.js" in the terminal, I encounter an error saying "Error: Cannot find module 'D:\nodeP\main.js'". This is confusing for me as I have set the environment variable path ...

Exploring the vueJS canvas life cycle and transitioning between components

Struggling with displaying Vue components that contain a canvas with different behaviors. Looking to switch components using v-if and passing different properties. Here's a small example: Currently, when switching from 'blue' to 'red ...

Modify an element on one webpage using a function called from another webpage

I am currently working on a website design that involves displaying images on various frames. While I have managed to change content across different frames, I am now exploring the possibility of changing content across different web pages. Here is the se ...

Updating the HTML class with JavaScript

My HTML class has two classes $(document).ready(function() { $(".container").hover(function() { $('.green').addClass('display-on'); }); $(".container").mouseleave(function() { $('.black&apos ...

Issue with Vue: Calling method instantly when using :mouseover in v-for within a component

Whenever I try to incorporate :mouseover in a v-for loop within the <component>, I encounter an issue. The method assigned to the :mouseover event is triggered for each element, rather than just for the hovered elements. <Single-technology ...

Activate a particular panel within the leftPanel using PDFNet Webviewer

When using disableElements in the setQuickBarPanelContents() function, I am able to remove 2 of the 3 panels from the leftPanel: setQuickBarPanelContents() { this.instance.disableElements(['notesPanel', 'notesPanelButton', &apos ...

Use Jquery to apply quotation marks within a blockquote

Here is the code I am working with: $("input[id="+id.slice(0,-1)+"-br-"+brand+"].qnt_to_cart").show(); This code generates: input[id=02620-br-FEBI BILSTEIN].qnt_to_cart However, I need it to look like this instead: input[id="02620-br-FEBI BILSTEIN"].q ...

Position the label and the select dropdown side by side within the sweetalert 2 component

Can anyone provide an example of aligning a label and dropdown in the same row using sweetalert2? I attempted to customize the label placement, but it appears on a separate line. I would like to log the selected dropdown item upon clicking the OK button. ...

increasing the size of the input thumb compared to the others

Hello fellow React developers, I'm currently learning by coding and I have a question about a slider. I'm trying to make the thumb of the slider bigger, but when I increase its size it doesn't fully display within the input area (as you can ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...