The Angular Router is continuing to show the HomeComponent upon navigation, rather than just displaying the ChildComponent

Lately, I've been diving into Angular and attempting to create a github search application using the github api. However, I've encountered some roadblocks with routing and data passing. My goal is for the user to land on a page like /user/userID upon clicking the view profile button. I have four components in place - home, list, 404, and app component. The issue arises when the URL changes upon button click, and although the list component renders, the main page content remains visible. I aim for the user to only see the child component content. In React, I typically resolve this problem using "exact", but I'm unsure of how to achieve the same effect in Angular. Additionally, when attempting to send data to the list component using Input(), the list component also displays on the main page. To provide more context, I have included screenshots and code snippets below.

Home page: https://i.sstatic.net/BGsPJ.png

user/userID page: https://i.sstatic.net/WmGBl.png

app.component.html :


  <ng-template [ngIf]="profile !== '' && user" style=" border: 5px solid black;padding: 2em;">
    <img [src]="user.avatar_url" alt="" style="width: auto; height: 100px;">
    <p>Username: {{user.login}}</p>
    <p>Location: {{user.location}}</p>
    <p>E-mail: {{user.email}}</p>
    <p>Blog Link: {{user.blog}}</p>
    <p>Member Since: {{user.created_at}}</p>
    <button href="#" [routerLink]="['/', user.login.toLowerCase(), user.id ]" style="padding: .5em;">View Profile</button>
  </ng-template>

<div>
  <app-list [data]="user"></app-list>
</div>

<div class="container">
  <router-outlet></router-outlet>
</div>

app.component.ts:

import { HttpService } from './http.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  user: any;
  profile: any;
  constructor(private userData: HttpService) {}

  ngOnInit() {
    
  }

  findProfile() {
    this.userData.updateProfile(this.profile);
    this.userData.getUser().subscribe((result) => {
      console.warn(result);
      this.user = result;
    });
  }

  title = 'my-app';
}

list.component.html:

<h1>list component</h1>

list.component.ts:

import { ActivatedRoute } from '@angular/router';
import { HttpService } from '../http.service';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
})
export class ListComponent implements OnInit {
  @Input() data: any;
  userID: any;
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe(
      params => this.userID = params['userID']
    );
  }

}

home.component.html:

<h1>home component!</h1> 

app-routing.module.ts:

import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ListComponent } from './list/list.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: ':user/:userID', component: ListComponent },
  { path: '**', component: PageNotFoundComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

Answer №1

Kindly consider making this adjustment

{ path: '', component: HomeComponent },

modify it to look like this:

{ path: 'home', component: HomeComponent },
{ path: '', redirectTo: 'home', pathMatch:'full'},
{ path: 'list/:user/:userID', component: ListComponent },

and also update this part:

[routerLink]="['/', user.login.toLowerCase(), user.id ]"

to read as follows:

[routerLink]="['/list', user.login.toLowerCase(), user.id ]"

The issue at hand is that HomeComponent is being displayed because the router still identifies it as a valid route for the path you are navigating towards. The path (without query parameters) remains empty. By changing the navigation path to '/list', the problem should be resolved.

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

Mocking an injectable Angular2 service

My setup involves Angular 2 Karma-Jasmine with a service called AService. it("test", () => { let x:any = function1('value', aService); expect(x).toEqual("value1"); }); AService now includes a method called getA(), and function1 relie ...

Ways to leverage Composite API in place of Mixin or Extends functionality

Currently, I am exploring the use of Vue3 for my project. One issue I am facing is that I need to create multiple components (SFC) with similar properties. I want to define these common properties using the composite API across all components, like so: con ...

What are the steps to troubleshoot server-side TypeScript code in NextJS with WebStorm?

I am struggling to debug the NextJS API in WebStorm while using TypeScript and navigating through the app route. It is proving to be quite challenging to efficiently debug the API without relying heavily on console.log(). ...

Issue encountered during execution of tests involving reactive forms

Having some issues with the code below and looking for a solution. The tests pass when mocking the form for ts tests, but encounter an error when mocking the same form for html: No value accessor for form control with name: 'Enable' If I remov ...

Tips on navigating an array to conceal specific items

In my HTML form, there is a functionality where users can click on a plus sign to reveal a list of items, and clicking on a minus sign will hide those items. The code structure is as follows: <div repeat.for="categoryGrouping of categoryDepartm ...

The items are not displayed in the app.component.html file

I am having trouble displaying the product list in an HTML file. Despite receiving the product data in a JavaScript message, it is not showing up when I try to list it in the HTML. Can anyone assist me in resolving this issue? Below is the code snippet: im ...

Keep track of the input values by storing them in an array after they are

Creating an Angular application to read barcodes. barcode-scanner.component.html <form #f="ngForm" class="mt-3 text-center" id="myform" (ngSubmit)="onSubmit(f)"> <div class="text-center"> <input type="text" maxlength= ...

What is the best way to implement an Angular Guard that utilizes an API service for validation and redirects in case of failure?

Hello there! I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decid ...

Tips for displaying dynamic Angular custom elements

I've been working on projects that have implemented the Angular web component concept, as outlined in the Angular guide. Currently, we only have 2 or 3 elements that are displayed dynamically based on user input. Once the user completes the form, the ...

Having trouble transferring data from indexedDB to an Angular Subject in order to utilize it within an Observable using ngx-indexed-db

When using ngx-indexed-db's getByKey method to retrieve data from indexedDB and passing it to the subject, there seems to be an issue. Although the data is successfully retrieved, an error occurs stating that the data is undefined when attempting to u ...

Encountering a challenge when upgrading to eslint version 9.0.0

Encountering an issue while trying to upgrade eslint to version 9.0.0. ⋊> ~/A/fusion on turborepo ⨯ bun lint 22:21:58 $ eslint packages/*/src/**/* Oops! Something went wrong! :( ESLint: 9.0. ...

Troubleshooting: Icon missing from React vscode-webview-ui-toolkit button

In the process of developing a VSCode extension using React and the WebUi Toolkit library for components, I encountered an issue with adding a "save" icon to my button. I diligently followed the documentation provided by Microsoft for integrating buttons i ...

Guide on properly specifying mapDispatchToProps in a component's props interface

In my project, I have a connected component utilizing mapStateToProps and mapDispatchToProps along with the connect HOC from react-redux. My goal is to create concise and future-proof type definitions for this component. When it comes to defining types fo ...

The Clerk authMiddleware() function has been defined in the middleware.ts file located at the root of the application, but it is not being utilized

import { authMiddleware } from "@clerk/nextjs"; export default authMiddleware({}); export const config = { matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)&apos ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

Angular has successfully subscribed to an Observable, however, it is not triggering a refresh or

I am currently implementing a notifications feature for my Angular application. Within the header: The header is only called once after logging in, displaying a badge with the count of unread notifications: <button mat-icon-button> <mat-ico ...

Setting up Tarui app to access configuration data

I am looking to save a Tauri app's user configuration in an external file. The TypeScript front end accomplishes this by: import {appConfigDir} from "tauri-apps/api/path"; ... await fetch(`${await appConfigDir()}symbol-sets.json`) { ... ...

The Angular Library seems to be malfunctioning as it does not execute the ngOnInit

I've been following the instructions from Angular CLI 6 to create a library, which can be found here. So far, I've successfully created and built my library. It includes a Component that I'm using for the UI and has an HTML selector. @Compo ...

Typeorm stored procedure that returns a JSON response

Whenever I execute the stored procedure defined in a Microsoft SQL database using TypeORM as shown below: const result=await conn.query('exec Spname @0,@1',[inp1val,inp2val]); I receive a response from the database, but it comes with an addition ...

Troubleshooting the challenge of transitioning from Angular 4 to Angular 9 with flatMap

In my Angular 4 code, everything runs smoothly: public resolve(): Observable<GridViewDtcConfig> { const permissionResponse = this.flowsService.getPermissions(); return permissionResponse.flatMap((permissions) => { c ...