Making an "associated" route the active route within Aurelia

In my Aurelia application, I have implemented two routes: a list route called Work and a detail route called WorkDetail.

Currently, only the list route is visible in the navigation menu:

Home  |  *Work*  |  Contact  |  . . .

When users navigate to the WorkDetail view, I want the Work route to be highlighted as active in the navigation menu.

To achieve this, I have attempted to set the route as active in the WorkDetail view's activate() callback and as inactive in the deactivate() callback:

import {inject} from 'aurelia-framework';
import {Router} from 'aurelia-router';

@inject(Router)
export class WorkDetail {
    constructor(router) {
        this.workRoute = router.routes[2].navModel;
    };

    activate(params, routeConfig, navigationInstruction) {
        this.workRoute.isActive = true;
    };

    deactivate() {
        this.workRoute.isActive = false;
    };
}

The issue I am encountering is that the "Work" navigation item does not appear as active on the initial activation. It only becomes active when navigating to another WorkItem.

Why is the nav item only becoming active after subsequent navigations? Is there a better approach to setting a parent or related navigation item as active?

If you are interested, here is a link to my app.js file: https://gist.github.com/alsoicode/37c5699f29c7562d2bf5

Answer №1

If my interpretation of the question is correct, it seems that you have a "Work" link in your navigation bar that opens a list of work items. When you click on an item in the list, you want the "Work" link to remain highlighted in the navigation bar even when viewing the detailed screen.

In a similar scenario I encountered in this project, here is how I approached it:

Firstly, configure the "work" route in app.js:

export class App {
  configureRouter(config, router) {
    config.title = 'Aurelia';
    config.map([
      { route: '', redirect: 'work' },
      { route: 'work', moduleId: './work/work-section', nav: true, title: 'Work' },
      // ... other top-level sections' routes ...
    ]);
    this.router = router;
  }
}

Create a "work" folder within your project. This folder will contain all views and view-models related to "work".

Inside the "work" folder, add "work-section.js":

/**
* The main component for the work section of the application. It will display either
* the list of work items or the detailed information of a specific work item.
*/
export class WorkSection {
  configureRouter(config, router) {
    config.map([
      { route: '',    moduleId: './work-list',   nav: false, title: '' },
      { route: ':id', moduleId: './work-detail', nav: false, title: '' },
    ]);
  }
}

Add "work-section.html" in the same folder - it will simply include a <router-view>:

<template>
  <router-view></router-view>
</template>

Lastly, include your work-list.js + .html and work-detail.js + .html files in the "work" folder. By clicking on the "Work" link in the navigation bar, the list of work items will be displayed initially. Even when you navigate to a specific work item's details, the "Work" link in the navigation bar will stay active.

Feel free to explore the demo application. It showcases three main sections (orders, customers, and employees), each following the same approach. You can also access the source code here.

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

The reason behind the creation of .pnp.loader.mjs and .pnp.cjs files by yarn

While working on my React project with Vite, I noticed that when using yarn to start the "live server," two new files are created: .pnp.loader.mjs and .pnp.cjs. Can anyone explain what these files are for? I've never come across them before as I usual ...

Can the value of a key be changed to match the condition in a find() query when using Mongoose?

Having been well-versed in Oracle, I was thrown into a project requiring the use of a MongoDB database. Utilizing mongoose to connect to my MongoDB, my main query is whether it is possible to match a find condition before executing a query. For example, if ...

CSS styling doesn't take effect until the page is reloaded due to the failure of cssText

After generating a new list item, it appears that the CSS styling is not being inherited until the page is reloaded. Even though I have added styling using cssText dynamically, it doesn't seem to be working as expected. I've attempted using cssT ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

The infinite scroll feature on Next.js resulted in duplicating the last element during the initial fetch process

I have a project that involves fetching data from Strapi Rest API using Next.js. I am fetching and displaying cards based on the fetched content. To prevent loading all the data at once, I have implemented an infinite scroll feature using react-infinite-sc ...

Comparing two inherited classes in Typescript: A step-by-step guide

Let's say we have two classes: Animal and Dog. The Dog class is a subclass of the Animal class. I am trying to determine the types of these objects. How can I accomplish this task? class Animal {} class Dog extends Animal {} //The object can be of ...

`Creating a fluid MySQL table using JavaScript`

One of the challenges I'm facing involves working with a MySQL table that consists of 3 columns: MySQL db table +--+----+-------------+ |id|data|display_order| +--+----+-------------+ |0 |0 |2 | +--+----+-------------+ |1 |1 |1 ...

Disabling a button based on the state of a switch button using React and Material UI

For the task at hand, we need to ensure that the button is only activated when the switch button's state changes. This state is received as a prop and needs to be validated correctly within the handleChangeState function. const CustomSwitch = ({name, ...

unable to transfer PHP variable into a JavaScript function

I am having trouble invoking a JavaScript function when trying to pass a PHP array element as an argument. Despite my efforts, I have not yet found the solution. Here is the snippet of PHP code where the issue arises: var_dump($theRow[11]); $htmlBuffer = ...

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Switch the dropdown menu to a button if it consists of only one option

I have been using a database within the Moodle Learning Management System that generates a bootstrap table. Here is an example of what it looks like: https://i.sstatic.net/UJc4M.png The last row in the table contains a dropdown menu. When viewing your ow ...

Add opening and closing HTML tags to enclose an already existing HTML structure

Is there a way to dynamically wrap the p tag inside a div with the class .description-wrapper using JavaScript or jQuery? This is the current html structure: <div class="coursePrerequisites"> <p> Lorem ipsum.. </p> </ ...

Managing an Infinite Amount of Inputs in React

I'm designing a React component that enables users to send emails to their friends and family. By default, the component includes 3 input fields, but users can easily add more by clicking a button. To implement this feature, I plan to create a button ...

Data is not being refreshed by Ajax

In my forum, users are only allowed to edit and delete their own comments. I have set up an "edit" button that opens a modal when clicked, giving the user access to the data they submitted before. I've written an ajax function to target these fields a ...

Inject the JavaScript template into an HTML page within a <div> element

Looking for a solution to format JSON API data listing books with title, author, and other properties into HTML? Utilizing ES6 backticks and JavaScript templating, the challenge arises when needing to display two cards per row on the HTML page. The issue l ...

Experiencing difficulties integrating react-moveable with NEXTjs: Error encountered - Unable to access property 'userAgent' as it is undefined

I've been grappling with this problem for the past few hours. I have successfully implemented react-moveable in a simple node.js app, but when I attempt to integrate it into a NEXTjs app, an error crops up: TypeError: Cannot read property 'userAg ...

When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...

Condition-based React state counter starts updating

In my current project, I have developed the following React component: import React from "react"; import ReactDOM from "react-dom"; import { WidthProvider, Responsive } from "react-grid-layout"; import _ from "lodash"; const ResponsiveReactGridLayout = Wi ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...

Step-by-step guide for implementing a scroll event on FancyBox

I am facing an issue with a large fancybox popup that contains a scroll function. I need to find a way to attach an event to this fancybox popup when scrolling. I have tried several different events, such as: $('.fancybox-inner').off("scrol ...