The navigation bar changes its functionality depending on the page

My Angular application features a main app component that includes a navbar linking to other components using the routerLink directive. The structure is simple:

<nav>
    <button [routerLink]="['/foo']>
        Foo
    </button>
    <button id="button_to_change" [routerLink]="['/bar']>
        Button I want to customize
    </button>
</nav>
<div [@routeAnimation]='prepRouteState(routerOutlet)'>
    <router-outlet #routerOutlet="outlet"></router-outlet>
</div>

In a specific component (for example, the foo component in the mentioned scenario), I want to modify the behavior of the second button bar only within that component. Is it possible to achieve this programmatically through TypeScript code? Can I change the destination of the bar button for that particular component?

Appreciate any guidance on this matter

Answer №1

For greater flexibility, opt for (click)="barClicked()" over [routerLink]="['/bar'] when handling dynamic actions.

Answer №2

To determine which component is being loaded and control the visibility of buttons accordingly, you can subscribe to router events in your application and implement the logic for showing or hiding each button.

For example, in your navbar component:

class Navbar {
  showButton: boolean = false;
  
  constructor(private router: Router) {
    router.events.subscribe((event) => {
      console.log(event instanceof NavigationEnd);
      
      if (event instanceof NavigationStart) {
        if (event.url === "yourcomponentroute") {
          this.showButton = true;
        }
      }
    });
  }
}

Your navbar HTML template should look like this:

<nav>
    <button [routerLink]="['/foo']">
        Foo
    </button>
    
    <button *ngIf="!showButton" id="button_to_change" [routerLink]="['/bar']">
        Button for other components
    </button>
    
    <button *ngIf="showButton" id="button_to_change" [routerLink]="['/bar']">
        Button for foo component
    </button>
</nav>

Answer №3

Here's another method using *ngIf with a getter and a service to manage the current page:

Define your service:

@Injectable()
export class PageService {
    currentPage: string;
}

Implement in your navigation component:

<nav>
    <button [routerLink]="['/home']>
        Home
    </button>
    <button *ngIf="currentPage=='page1' [routerLink]="['/page1']>
        Page 1
    </button>
    <button *ngIf="currentPage=='page2' [routerLink]="['/page2']>
        Page 2
    </button>
</nav>

export class NavigationComponent {
   get currentPage() {
       return this.pageService.currentPage;
   }
   constructor(private pageService: PageService) {}
}

Adjust your specific component:

export class Page1Component implements onInit {
   set currentPage(value) {
        this.pageService.currentPage = value;
   }
   constructor(private pageService: PageService) {}
   ngOnInit(){
       currentPage = "page1";
   }
}

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

Utilizing Typescript to pass props to a material-ui button enclosed in styled-components

After setting up my react project using the typescript template, I decided to style the material-ui Button component using the 'styled' method from the styled-components library as shown below: import React from 'react'; import styled f ...

Error when sending Angular 4 GET request with multiple Headers results in a 400 bad request code

I've been attempting to perform a POST request with headers in order to receive a response. The Angular code snippet I'm currently using for this request is shown below: const headers = new HttpHeaders({ 'Content-Type': 't ...

Upgrading to Angular 6 causes Linter to become significantly more stringent

Recently, I made the jump to Angular 6 and am currently in the process of deploying it. However, I have encountered a major roadblock. The latest issue that I'm facing is an extremely strict linter. When I try to deploy my application using firebase d ...

Utilize the gsap ScrollTrigger in conjunction with React's useRef() and Typescript, encountering issues with type mism

Recently, I've been trying to add some animation to a simple React Component using the GreenSock ScrollTrigger plugin. However, I ran into an issue due to types mismatch in my Typescript project. Here's a snippet of the code: import React, {useRe ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

Encountering an error message in Angular stating "Spotify is not defined" while utilizing "@types/spotify-web-playback-sdk"

I'm currently integrating Spotify's web player SDK into an Angular project. I followed the steps outlined in this particular question and answer: Installing the types package, then including the types reference at the beginning of the file where ...

How can Angular 6 automatically detect changes in angular2-cli app files and run build files on the browser simultaneously?

I have an angular2-cli app and I want the build files to automatically detect changes when I view them in a browser. How can I achieve this? I tried using the following command: ng build --prod --build-optimizer --watch Once the build files are crea ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

Use the date-fns max function to identify the latest date in an array of date strings

The Dates string array is created using data from the backend object in the following manner: const dates: string[] = this.data.map((item:any) => item.date.jsdate); Here is the resulting array: dates = [ Thu Jan 12 2015 00:00:00 GMT+0530 (India T ...

React-aria | Encountering a typescript error with input fields/textfields

Seeking assistance with using react-aria, specifically the useTextField feature. Despite following the documentation available at , I encountered an error related to the input element. Any help would be appreciated. Code import { AriaTextFieldOptions, use ...

Using Vanilla JavaScript library in Angular 6 - A Comprehensive Guide

I encountered an error while trying to import a Vanilla JavaScript library into an Angular 6 component. Can you please provide me with some guidance on how to resolve this issue? This is the syntax I used to import the library: import * as ExistingLibrar ...

The tslint exclusion is not functioning properly for tsoa endpoints

I'm trying to remove the routes.ts file generated by tsoa routes from being compiled by tslint. I've used the exclude option but it doesn't seem to be working specifically for routes.ts. The exclude option works for other files, except for r ...

In Angular 10, the custom CSS URL is loading after the standard styles.css file

Below is the configuration from my angular.json file: "options": { "outputPath": "dist/example", "index": "src/index.html", "main": "src/main.ts", ...

Angular's async pipe will not refresh the view until the user interacts with it

Within my app, I have a straightforward service named ActionBarService that emits TemplateRefs. Despite subscribing to the stream using the async pipe in the app-component and receiving the emitted value as expected, the new template is not rendering until ...

Is there a comparable feature in Typescript similar to Java/.NET Reflection? Alternatively, how can I retrieve a list of classes that inherit from a specific abstract class?

People call me Noah. // CreaturesBase: installed through 'npm install creatures-base' export default abstract class Animal {...} We have this abstract base class called Animal, which comes from a third-party package on npm. Other packages exten ...

Typescript constructor that accepts an object as an argument instead of traditional parameters

My constructor is becoming lengthy and not structured the way I would prefer. I am looking to pass an object to my constructor so that I can access fields by their names. Here is how the class looks currently. export class Group { id: string; constru ...

Setting the location of the global nprmrc file on a Windows operating system

Is it possible to change the default global npmrc location in Windows operating systems? ...

When TypeScript tsc is unresponsive, there is no output or feedback provided

Just getting started with TypeScript! I've been working on transitioning my React.js project from JavaScript to TypeScript. I managed to resolve all the bugs and verified that it runs smoothly when using npm start. However, whenever I try to comp ...

Modifying an Angular Component Template following an API Response

As someone relatively new to Angular, I come with some experience from working with other JavaScript frameworks like Vue and React. Currently, I am developing an Angular Lab application that interacts with 2 APIs to retrieve information. After receiving th ...

The connection to Firebase is being refused when attempting to use the http.post method in Ionic

In my Ionic 3 Angular app deployed on Firebase static hosting, the problematic section of code appears as follows: var data = {"message" : time, "user_id" : user}; return new Promise((resolve, reject) => { ...