Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies.

Afterward, I connected all the routes to their respective Components as follows:

import {ModuleWithProviders} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {AttendanceComponent} from './attendance/attendance.component';
import {LoginComponent} from './login/login.component';

//Route Configuration
export const routes: Routes = [
  {path: '', component: LoginComponent},
  {path: 'attendance', component: AttendanceComponent}
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

I initialized my app in my app.module:

import { Component, NgModule } from '@angular/core';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

//declarations
import { AppComponent } from './app.component';
import { LoginComponent } from  './login/login.component';
import { AttendanceComponent } from './attendance/attendance.component';
import { routing, routes } from './app.routes';

//decorator
@NgModule({
  imports:      [
      BrowserModule,
      FormsModule,
      HttpModule,
      routing,
      RouterModule
    ],
  declarations: [
        AppComponent,
        LoginComponent,
        AttendanceComponent
      ],
  //add services
  //providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
  bootstrap: [ AppComponent ]
})
export class AppModule {
  //module class
}

In my app.component, a call is made to the landing page

import {Component} from '@angular/core';
import {LoginComponent} from './login/login.component';

@Component({
  selector: 'oosc_app',
  template: `<login></login>`
})

export class AppComponent{
}

The landing page is login.template.html:

<body class="login">
<div id="login" class="login-position>
        <div class="logo">
            <a href="index.html"><img src="assets/images/oosc-logo-login.png" alt="" /></a>
        </div>

        <div class="wrapper-login">
            <input type="text" placeholder="TSC Number" class="user"/>
            <input type="password" placeholder="Password" class="password"/>
        </div>

        <!--<a [routerLink]="['/attendance']" class="login-button">Sign in</a>-->
        <a [routerLink]="['/attendance']"  class="login-button">Sign in</a>
        <router-outlet></router-outlet>
        <span>Not a member ?<a href="#">Create your account</a></span>
    </div>
</body>

Upon clicking the sign-in button, the router link should direct to attendance.component.ts and display the view.

The issue arises when the sign-in button is clicked, it redirects to localhost:3000/attendance but fails to switch from the login view to the attendance view.

Below is my attendance.component.ts:

//The content has been split into headers and footers with the templateUrl being called
//in a component named Content

import {Component} from '@angular/core';
import {OnInit} from '@angular/core';
import {HeaderComponent} from '../partials/header.component';
import {FooterComponent} from '../partials/footer.component';
import {ContentComponent} from '../partials/content.component';

@Component({
  selector: 'attendance',
  //templateUrl:  `/app/attendance/attendance.template.html`
  template: `<header></header><footer></footer>`,
  providers: [HeaderComponent, ContentComponent, FooterComponent]
})

export class AttendanceComponent implements OnInit{
  ngOnInit(){
    console.log('ngOnInit');
  }
}

What could be causing this problem?

Why is it not navigating to the correct view?

Answer №1

The issue lies in the absence of the router-outlet component in your template.

template: `    
    <router-outlet></router-outlet>

    <!-- not necessary -->
        <login></login>      
    <!-- you no longer need to use the <login> tag as your router will automatically load 
          the login component into the router-outlet due to the default path being set-->

`

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

Error in parsing: An unexpected symbol appeared, an identifier or keyword was expected at the end of the expression

Whenever I attempt to display data from an API, an error always pops up. My goal is to showcase each piece of data individually. To help you analyze the issue, I've included the URL of the API below: civilizationes.component.ts import { Component, O ...

Is it possible in TypeScript to change a string literal type into a number type?

Would it be feasible to develop a utility type Number<T> that can take a string literal type and convert it into a number? If conversion is not possible, should the utility return a never type? type Five = Number<'5'> // `Five` is con ...

Using href with IconButtonProps is not supported

I'm facing a challenge in creating a wrapper for the IconButton. I aim to pass components or href props, but unfortunately, I am unable to achieve this by passing the IconButtonProps. Is there a way to accomplish this? function CustomIconButton(props ...

The functionality of translations within a TypeScript object is currently malfunctioning

I am facing a perplexing issue with my code. I am utilizing lingui for internationalization in my application. The translations are stored using the `t` macro in a TypeScript object, which can be found here: https://github.com/Flaburgan/disco2very/blob/mas ...

Understanding a compound data type in TypeScript

Hey there, I'm new to TypeScript and I'm facing a challenge in defining the type for an object that might have the following structure at runtime: { "animals" : [ { name: "kittie", color: "blue" }, { name: ...

What is the best way to ensure the website theme remains consistent after a refresh in React?

I am currently enhancing a weather forecast website by incorporating a theme toggler feature. The functionality has been successfully implemented, but I am facing an issue where the selected theme does not persist after reloading the page. Can someone he ...

Ways to eliminate angular-fontawesome from a project?

I initially added Angular fontawesome to my project using the command provided in this link: https://www.npmjs.com/package/@fortawesome/angular-fontawesome ng add @fortawesome/angular-fontawesome@6 However, I have now decided that I want to switch to Font ...

Guide to dynamically configuring ViewEncapsulation for a Web Component

When initializing a component, I am facing an issue with setting up Shadow DOM based on the browser type (since IE does not support Shadow DOM). To handle this, I check if the browser is IE11 and then configure the encapsulation as Emulated for IE and Sha ...

Tips for choosing and filtering the preferred object in ES6

Consider this array structure: const testData = [ { group: "Team1", info: [ { key: 123, person: "Alice", type: "Football" }, { key: 456, person: "Bob", type: " ...

Attempting to implement endless scrolling functionality using rxjs and angular 2 framework

I'm struggling to understand how I can incorporate stream data into my infinite scroll feature. First, I define my observable variable and page offset: products$; offset: number = 0; Next, I create an observable using one of my services: this.prod ...

What is the best way to modify the disabled attribute?

After disabling a button using a boolean variable, updating the variable does not remove the disabled attribute. How can I update my code to enable the button when the variable changes? Here is my current code snippet: var isDisabled = true; return ( ...

Firestore data displaying as null values

Recently, I encountered CORS errors while polling the weather every 30 seconds in my program. Upon investigating, I discovered that the city and country were being interpreted as undefined. To fetch user data from my users' table, I utilize an Axios ...

Is it possible for a button to be assigned to a variable upon creation, but encounter an error when trying to

const button:Element = document.createElement("button");//This works fine const button:HTMLButtonElement = document.createElement("button");//This works too const button2:Element = document.getElementsByTagName("button");//Why does this give an error? con ...

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Learn the process of importing data types from the Firebase Admin Node.js SDK

I am currently facing a challenge with importing the DecodedIDToken type from the https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth.decodedidtoken. I need this type to be able to assign it to the value in the .then() callback when v ...

Angular SwitchMap is a powerful operator that allows you

I am currently utilizing the mat-table component from angular material, in conjunction with pagination features. Whenever a user inputs text into the search field, a filter method is activated to send the text, page size, and current page to the backend f ...

Test for comparing objects partially using Jasmine Array

Is there a specific method in jasmine for checking if an array partially matches another array by comparing objects? Considering that the arrays could potentially contain large amounts of data from test files, is there a way to avoid comparing each indivi ...

Personalizing the mat-checkbox

I'm trying to customize the checked icon in angular material mat-checkbox. Currently, it displays a white tick icon inside a colored background box, but I want to replace the tick with a cross when it is checked. After spending all day searching, I ha ...

Retrieve a specific value from the NGXS state by providing a parameter

I have a unique situation where my state contains JSON data like this: {id: "1", name: "ig1", description: "ig 11"} {id: "5", name: "hhh", description: "hhh"} {id: "6", name: "ggg", description: "hhh"} My goal is to specifically extract the data for id = ...

What is the optimal method for navigating through a complex nested object in Angular?

Looking to navigate through a nested object structure called purchase. Within this structure, there is a sub-array named purchaseProducts which contains another sub-array called products along with additional data. What methods do you suggest for efficien ...