Angular 2 - Beginner's guide to updating the header when navigating to a new route or page

SOLVED

I am faced with a challenge involving multiple components in Angular2. Specifically, I have the following components: home component, default header, detail component, and detail header component. Each header has a unique layout.

At the Home page, the 'Default header' is displayed. However, when a user navigates to the Detail Page, the 'Detail Header' should be shown instead.

My initial logic was to use an if else statement in the app.component.ts file to achieve this toggle functionality. Unfortunately, the headers are not switching as expected.
Can anyone provide guidance on how to properly implement this feature in Angular2? I seem to be struggling with adapting the headers based on the current page.

Below is the snippet from my app.component.ts:

@Component({
  selector: 'app-root',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./main.css'],
  template: `
    <div class="main-body">
      <app-header *ngIf="!showHeaderB()"></app-header>
      <detail-header *ngIf="showHeaderB()"></detail-header>
      <div class="container">
        <small><api-error></api-error></small></div>
        <router-outlet></router-outlet>
      </div>
      <app-footer></app-footer>
      <template ngbModalContainer></template>
    </div>
  `
})

export class AppComponent {
  showHeaderB(){
    if (this.router.url.startsWith('/detail/')) {
      return true;
    } else {
      return false;
    }
  }
}

Answer №1

One way to enhance your components is by creating a separate page-header component.

@Component({
  selector: 'page-header',
  template: `
    <div> {{title}}</div> 
  `,
})
export class PageHeader {

  @Input() title:string="";

}

To implement this, you would need to include the page-header component in each of your components and assign a title to it.

@Component({
  selector: 'component-1',
  template: `
    <div>
      <page-header title="pageTitle"> </page-header>
      ...
    </div>
  `,
})

export class Component1 {

pageTitle:string;

}

@Component({
  selector: 'component-2',
  template: `
    <div>
      <page-header title="pageTitle"> </page-header>
      ...
    </div>
  `,
})

export class Component2 {

pageTitle:string;

}

Answer №2

Consider updating the showHeaderB() method as shown below:

Imagine you have a URL like localhost:8080/..../..../detail/.... and the position of "detail" is 4. In this case, set the parameter for position 4.

showerHeaderB(){
    if (this.router.url.startsWith('/detail', 4)) {
        return true;
     } else {
            return false;
      }
    }

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

What is the process for updating variable values in an angular service.ts file?

Being a newcomer to programming and the angular framework, my question may seem too obvious. I have a service.ts file that interacts with Firebase to implement CRUD operations. Inside Firebase, I have a filter function that relies on the value of the vari ...

Tips for debugging and stepping into an npm package containing Typescript source code

Okta, an Angular NPM dependency, is not functioning as expected for me. I am in need of diving into its source code while debugging my application to troubleshoot and resolve the issue at hand. How can I achieve this within my Angular 6 app? Despite using ...

Exploring the ambiguity of explicit types with type generics

I am facing a type error issue with a Higher-Order Component (HOC): Error: Type 'number[]' is not assignable to type 'string'. Here is how I set up my HOC: const ComponentPage = renderPage(Component); However, I encounter the error ...

Angular 10 - unable to bind 'formGroup' as it is not recognized as a valid property of 'form'

In my existing Angular application, I need to implement routing and a login page as the functionality expands. To integrate routing, I have included the following code: app.module.ts // Importing various modules @NgModule({ declarations: [ App ...

The Dynamic Duo: Typescript and Knex

I'm new to TypeScript and currently working on a node application using Express, Postgresql, and Knex. I'm a bit confused about when to apply type definitions in my code. Looking at other projects for guidance has left me even more puzzled as to ...

What is the best way to prevent the hassle of manually reloading a VS Code extension each time I make updates

While working on my VS Code extension, I keep encountering the issue of opening a new instance of VS Code every time I run the extension to view recent changes. This becomes especially tedious when using VS Code remote and having to enter my password twice ...

A step-by-step guide on creating a Decorator using the TypeScript compile API

How can I create a custom class in TypeScript with multiple 'class-validator' decorators to ensure the property types are correct? I am considering using `ts.factory.createDecorator`, but I'm unsure how to obtain a `ts.Expression` for it. ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

The type 'Argument of (props: ITableProps) => JSX.Element' cannot be assigned to the parameter type of... - React High Order Component

One of the tools I have in my arsenal is a loader HOC This is how the HOC looks like: const withLoader = <P extends object>(WrappedComponent: new () => React.Component<P, any>, loading: boolean) => { return class WithLoading extends ...

Displaying personalized message 'Loading...' while waiting for the data to be retrieved from the API

How can I display a 'Loading' text message until the data is fetched from the API? Currently, it just shows a message saying 'No data to display' I have searched through the documentation but couldn't find any related information. ...

A keyboard is pressing on tabs and navigating through the app's contents in Ionic 3 on an Android device

I'm currently working on an IONIC 3 app and facing a challenge. When I tap on the ion search and the Keyboard pops up in ANDROID, it disrupts the layout by pushing all the content around. Original screen: https://i.sstatic.net/34iBz.jpg Keyboard m ...

Having trouble with the npm Fluid Player installation

I am attempting to integrate Fluid Player into my Angular application Using - npm i fluid-player However, I'm encountering this error ...

Discovering all subclasses of a base class in AngularWould you like to learn how

abstract class Item { private name: string; private description: string; constructor(name: string,description:string) { this.name = name; this.description = description; } } class Car extends Item { constructor(name: string,descri ...

How can I retrieve a targeted set of information from Firebase Realtime Database?

Any suggestions on how to improve querying a specific data set in Firebase RTDB? I've been using forEach() and pushing to a BehaviorSubject inside subscribe for each observable emitted. Share any alternative approaches you have! I've hit a roadbl ...

Error occurs on Chrome while Angular 7 HTTP POST works fine on Edge and Firefox

My application is experiencing a strange issue where the HTTP POST method works fine on Firefox and Edge browsers, but not on Chrome. The application is built using Angular 7 and .NET Core 2.2. It has a CRUD example that functions correctly in all browser ...

Discover the Category of Union based on Discriminator

Imagine a scenario where there is a concept of a union type called Thing, which combines types Foo, Bar, and Baz, each identified by the property tag. interface Foo { tag: 'Foo' foo: string } interface Bar { tag: 'Bar' bar: nu ...

Making sure that a commitment does not come to fruition

Perhaps this code snippet below functions correctly as it is, but I'm uncertain if it's the best approach to prevent potential runtime issues. Here's the code in question: const ep = `${environment.api.baseUrl}/login`; return this.http.pos ...

The softAssert method is not available when trying to implement soft assertions within a TypeScript-based Protractor framework

Uncaught TypeError: assertion.softAssert is not a function I recently included a package called soft-assert using npm in my project. To install this package, I executed the following command: npm i soft-assert -g --save-dev Incorporated the following co ...

Convert the generic primitive type to a string

Hello, I am trying to create a function that can determine the primitive type of an array. However, I am facing an issue and haven't been able to find a solution that fits my problem. Below is the function I have written: export function isGenericType ...

Typescript issue when a value is possibly a function or null

I have defined a type called StateProps with the following properties type StateProps = { isPending: boolean, asyncFn: (...args: any[]) => void | null } To initialize, I set up an initialState variable where the asyncFn property is initially s ...