I am facing the issue of being unable to bind to 'routerlink' because it is not recognized as a known property of 'a', even after I have declared RouterModule in my app.module

Encountering a template parse error when using [routerlink] in an HTML page, despite importing RouterModule. Here's the relevant HTML snippet:

<mat-toolbar color="primary">
  <h3 [style.color]="white">ADMIN PORTAL</h3>
  <span class="spacer-left"></span>
  <button mat-button *ngIf="islogged"> View Book Lists </button>
  <a mat-button *ngIf="islogged" [routerlink]="['/addNewBook']"> Add a Book </a>
  <button mat-button *ngIf="islogged" (click)="logout()"> Logout </button>
</mat-toolbar>

Note: The usage of Angular Material design is evident.

Below is the app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { MaterialModule } from './material.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import 'hammerjs';
import { NavbarComponent } from './components/navbar/navbar.component';
import { LoginComponent } from './components/login/login.component';
import { LoginService } from './services/login.service';
import { AddNewBookComponent } from './components/add-new-book/add-new-book.component';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    LoginComponent,
    AddNewBookComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    routing,
    BrowserAnimationsModule,
    MaterialModule,
    FormsModule,
  ],
  providers: [LoginService],
  bootstrap: [AppComponent]
})
export class AppModule { }

It should be noted that RouterModule was implicitly imported through the routing variable exported in a separate TypeScript file:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from '../app/components/login/login.component';
import { AddNewBookComponent } from '../app/components/add-new-book/add-new-book.component';

const appRoutes: Routes = [{
    path: '',
    redirectTo: '/login',
    pathMatch: 'full'
  }, {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'addNewBook',
    component: AddNewBookComponent
  }
]
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

Despite importing RouterModule in the above file, encountering a detailed browser error as shown below:

Uncaught Error: Template parse errors: Can't bind to 'routerlink'
since it isn't a known property of 'a'. (">   <button mat-button
*ngIf="islogged"> View Book Lists </button>   <a mat-button *ngIf="islogged" [ERROR ->][routerlink]="['/addNewBook']"> Add a Book </a>   <button mat-button *ngIf="islogged" (click)="logout"):
ng:///AppModule/NavbarComponent.html@4:33
... 

Any assistance would be greatly appreciated. Thank you for your response in advance.

Answer №1

Make sure to use routerLink with an uppercase 'L', not 'routerlink'.

Additionally, it's recommended to follow SiddAjmera's example and separate the app.routing file for better organization.

Answer №2

It appears that the RouterModule has not been imported in your app.module.ts file. It is necessary to import the RouterModule.

UPDATE

To properly set up the routes, you should create a module for them as shown below:

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

Lastly, make sure to import the AppRoutingModule into your app.module.ts file.

Answer №3

An effective approach would be to develop a module

...
import { Routes, RouterModule } from '@angular/router';
...

const appRoutes: Routes = [...]

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

Then include AppRoutingModule in the imports array of your AppModule:

...
import {AppRoutingModule} from './app.routing';
...

@NgModule({
  ...
  imports: [
    ...
    AppRoutingModule
  ],
  ...
})
export class AppModule {}

By exporting the RouterModule from the AppRoutingModule, you can access all the functionalities provided by the RouterModule within the AppModule

Additionally, remember it is routerLink not routerlink (in Camel Case)

Answer №4

Property binding is sufficient for anchor tags, square brackets are not necessary.

The routes for navigation are constant, allowing you to use a string assignment for routerLink (a "one-time" binding).

Check out the documentation on Angular routers

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

To subscribe to the display of [Object Object], you cannot use an *ngIf statement without being inside an *ngFor loop

In my angular Quiz project, I have a functionality where every user can create quizzes. I want to display all the quizzes that a logged-in user has completed. Here is how I attempted to achieve this: // Retrieving user ID and category ID inside Re ...

Which flow is best for single page applications: Implicit or Authorization Code in OpenID Connect?

OIDC offers multiple authentication flows, with Implicit and Auth Code flow being the two primary options available for SPAs. Recent discussions in the ietf mailing list suggest that Auth code flow is preferable to implicit flow due to security concerns su ...

What is the method to incorporate @angular/fire into an Nx Workspace for an Angular project?

Incorporating @angular/fire into my Nx workspace for my Angular application is my current goal. Despite my efforts to adhere to best practices, I have not found any guidance in the official documentation on how to incorporate this library into the wor ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

What is the process for removing a particular file from my bundle?

I am currently utilizing webpack to build my angular2/typescript application and have successfully generated two files, one for my code and another for vendors. However, I am in need of a third file to separate my config (specifically for API_ENDPOINT) whi ...

Failure to trigger the before-prepareJSApp hook in nativescript-dev-webpack

I am currently facing some challenges while trying to bundle my Nativescript app using webpack. The first issue arises when I run the following command: tns build android --bundle After running this command, it seems like webpack is not doing anything. ...

Angular 4 project encountered a running error with the following issue displayed

While developing an Angular 4 app in Visual Studio within the same solution as the backend, everything was running fine. However, after adding some services and installing the Moment package, I encountered the following error: I attempted to reinstall pa ...

The deployment on Heroku is encountering issues due to TypeScript errors related to the MUI package

As someone relatively new to TypeScript and inexperienced in managing deployments in a production setting, I've been working on a project based on this repository: https://github.com/suren-atoyan/react-pwa?ref=reactjsexample.com. Using this repo has a ...

Setting up the propTypes for interface in React TypeScript

How can I specify the correct PropTypes for a property that is an interface in TypeScript with PropTypes? Requirements - Implementing both TS and PropTypes. Goal - To have a more precise type definition than PropTypes.any that meets standard eslint an ...

Discovering the breakpoints for Angular ng-bootstrapUncover the angular ng

Utilizing ng-bootstrap in my latest project has allowed me to easily create a grid with breakpoints, like so: <div class="row"> <div class="col-sm-12 col-md-6 col-xl-4"></div> </div> Although these breakpoints are convenient, ...

Updating a boolean value when the checkbox is selected

Hey there! I'm currently working on a project using Angular and have a collection of elements that can be checked, which you can check out here. In terms of my business logic: stateChange(event: any, illRecipe: Attendance){ var state: State = { ...

Importing/Requiring an External Module in Typescript Node using a Symbolic Link in the

I am in the process of migrating a Node + Express application to TypeScript and have encountered an issue with using external modules. Previously, I was utilizing the "symlink trick" to avoid dealing with relative paths. This is how it used to work withou ...

What is the method for utilizing a function's input type specified as "typeof A" to output the type "A"?

Check out this example from my sandbox: class A { doSomething() {} } class B {} const collection = { a: new A(), b: new B() } const findInstance = <T>(list: any, nonInstance: T): T => { for (const item in list) { if (lis ...

The meaning behind a textual representation as a specific type of data

This snippet is extracted from the file lib.es2015.symbol.wellknown.d.ts interface Promise<T> { readonly [Symbol.toStringTag]: "Promise"; } The concept of readonly seems clear, and the notation [Symbol.toStringTag] likely refers to "'toStr ...

Clear drop down selections after button is pressed

I am currently working with a grid in my template that contains multiple dropdowns, each row having its own. When I click a button, I gather the values from these dropdowns. However, upon clicking this button, I wish to reset all the dropdowns back to thei ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

Typescript for managing the Shopify admin API

Is there anyone who can confirm whether Shopify offers typescript definitions for their admin API? I'm specifically interested in finding types for Orders, Products, and Variants. I initially assumed that this package would have them, but it seems l ...

Tips for leveraging stage 3 functionalities in TypeScript?

Array.prototype.at() is currently in the proposal stage 3. Even after adding "lib": ["ESNext"] to my tsconfig.json, I encountered the error: Property 'at' does not exist on type 'number[]'. Could you shed some light ...

What is the process for inputting a predefined function into an interface?

In my project, I have a Locale interface that defines the properties of a locale for my component: interface Locale { src: string; alt: string; language: string; i18nFormat: string; } During debugging, I am using the built-in .toSource() function ...

Issue ( Uncaught TypeError: Trying to access a property of undefined ('data') even though it has been properly defined

One of my custom hooks, useFetch, is designed to handle API data and return it as a state. useFetch: import { useState, useEffect } from "react"; import { fetchDataFromApi } from "./api"; const useFetch = (endpoint) => { const [d ...