Tips for utilizing RouterLink within an HTML template

Angular 2.3.0

I created a module in Angular 2 as shown below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';

import { AppComponentRoute }  from './components/+app/index';
import { AppComponent }  from './components/+app/app.component';
import { HomeComponentRoute } from './components/+home/index';
import { HomeComponent }  from './components/+home/home.component';
import { ContactComponentRoute } from './components/+contact/index';
import { ContactComponent }  from './components/+contact/contact.component';

let app_routes: Routes = new Array();
    app_routes.push(AppComponentRoute);
    app_routes.push(HomeComponentRoute);
    app_routes.push(ContactComponentRoute);

@NgModule({
    imports:[
        BrowserModule,
        RouterModule.forRoot(app_routes)
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        ContactComponent
    ],
    bootstrap:[
        AppComponent
    ]
})

The Home Component is structured like this:

home.component.ts

import { Component } from '@angular/core';

@Component({
    selector: 'home',
    templateUrl: `./app/components/+home/home.component.html`
})

export class HomeComponent  { name = 'Home'; }

home.component.html

<nav>
    <a routerLink="/contact" routerLinkActive="active">Contact</a>
</nav>
<router-outlet></router-outlet>

The issue I am facing is that the routerLink attribute is not functioning when written in a separate .html file. Nevertheless, when I include the template directly within the component, it works smoothly:

@Component({
    selector: 'home',
    template: `
        <nav>
            <a routerLink="/contact" routerLinkActive="active">Contact</a>
        </nav>
        <router-outlet></router-outlet>
    `
})

How can I make this work in the external .html template?

UPDATE:

I forgot to mention the error message I encounter:

Can't bind to 'routerlink' since it isn't a known property of 'a'.

Thank you!

Answer №1

If you want to implement it, here is a suggestion:

<a [routerLink]="[ '/', 'about' ]" routerLinkActive="active">About</a>

To fit your specific routing structure, feel free to modify the first element in the array [routerLink]="[ '..', 'about' ]". Additionally, ensure that you include RouterModule in the imports section of your app.module.ts:

@NgModule({
  imports: [
    RouterModule,
    ...
    ]

Give it a try and see if it meets your needs!

Answer №2

It turns out that I have been utilizing gulp-htmlmin, which in turn relies on html-minifier. The default configuration for camelCase attributes is set to false, leading to the updated error message displaying routerlink instead of routerLink. This issue may seem quite subtle, so I hope this explanation proves helpful!

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

Oops! It seems like there is an issue with the Renderer2 provider in Angular v 4.1.3

Currently in the process of refactoring one of my services due to a breakage post-upgrade. I had to replace browserdomadapter(); along with several other deprecated methods. As a result of multiple deprecations starting around version 2.1 and various brea ...

Ways to access a nested route in Angular 4

My routing configuration is set up as depicted below: export const Approute: Routes = [ { path: '', component: DashboardComponent }, { path: 'add-course', component: AddCourseComponent }, { path: 'bui ...

Angular 4: Unable to attach 'ngModel' to 'input' as it is not recognized as a valid property

Before flagging as duplicate, please take a moment to review: Hello there! I am currently delving into the world of Angular 4 and ASP.Net Core, and I've encountered an issue that has been puzzling me. Despite exploring various similar problems where ...

Why does my useEffect consistently execute after the initial rendering, despite having specified dependencies?

const [flag, setFlag] = React.useState(false) const [username, setUsername] = React.useState('') const [password, setPassword] = React.useState('') const [errorUsername, setErrorUsername] = React.useState(true) const [er ...

I encountered an error stating "Buffer is not defined" originating from the Deode/Encode Stream Bundle.js script, not from my own code

I've encountered a major issue while attempting to update my npm project to webpack 5, and now I'm left with just one persistent error: bundle.js:1088566 Uncaught ReferenceError: Buffer is not defined at bundle.js:1044980:24 ...

Nest may struggle with resolving dependencies at times, but rest assured they are indeed present

I've encountered a strange issue. Nest is flagging a missing dependency in a service, but only when that service is Injected by multiple other services. cleaning.module.ts @Module({ imports: [ //Just a few repos ], providers: [ ServicesService, ...

The specified type '{ rippleColor: any; }' cannot be assigned to type 'ColorValue | null | undefined'

I've been diving into learning reactnative (expo) with typescript, but I've hit a roadblock. TypeScript keeps showing me the error message Type '{ rippleColor: any; }' is not assignable to type 'ColorValue | null | undefined' ...

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

By utilizing a function provided within the context, React state will consistently have its original value

After passing functions from one component to its parent and then through context, updating the state works fine. However, there is an issue with accessing the data inside these functions. They continue to show as the initial data rather than the updated v ...

AG-Grid: Enhancing Cell Interactivity

Within ag-grid, there is a feature called stopEditingWhenGridLosesFocus. I recently developed my own custom cell editor using a cell editor component. I am curious to know if there exists a similar property or method to achieve the behavior of stopEditing ...

script code to limit selection of dates within a predefined range

I'm seeking assistance to limit my customers from selecting a date beyond 10 days in advance. Although I previously had a code that functioned properly when there were more than 10 days left in the current month, it is now ineffective. This is becaus ...

Using TypeScript with Watermelondb

I'm currently developing a React App and I want to implement Watermelondb for Offline Storage, but I'm unsure about using it with TypeScript. I have already set up the database and created Course and Lesson model files from the Watermelondb libra ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

Angular neglects the specified animation timing

I created a sidebar component that relies on the sidebarExpanded state passed through Input(). Despite the correct animation trigger upon input change, the width adjustment happens abruptly. Interestingly, the same animation code works flawlessly in anothe ...

Getting an error message with npm and Typescript that says: "Import statement cannot be used outside

After developing and publishing a package to npm, the code snippet below represents how it starts: import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; export interface ... export class controlplaneDependencies ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

Mocked observables are returned when testing an Angular service that includes parameters

I'm currently exploring various types of unit testing and find myself struggling with a test for a service once again. Here is the function in my service that I need to test: Just to clarify: this.setParams returns an object like {name: 'Test&ap ...

The scope of the inferred type parameter in the generic TypeScript function is overly broad

I'm currently working on creating a function that takes in another function (a React component) as an argument and then returns a related function. My goal is to define specific requirements for the input function, ensuring that it accepts certain pr ...

encountered an error stating module '@angular/compiler-cli/ngc' could not be located while attempting to execute ng serve

Here is the content of my package.json file: { "name": "cal-euc", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build&qu ...

Propagating numerical values through iterative iterations

I am currently facing an issue with passing values as props to a component using the forEach method in JavaScript. In addition to passing the existing values from an array, I also want to send another value that needs to be incremented by 1 for each iterat ...