Nicky
Nicky

Reputation: 3827

How to use RouterLink in HTML template

Angular 2.3.0

I defined an Angular 2 module like so:

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 looks 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 problem is that routerLink is not working in the seperate .html file. However, when I define the template inline, I can use it like so:

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

How do I get this to work in the seperate .html template?

UPDATE:

I realized I forgot the error I'm getting:

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

Thanks!

Upvotes: 1

Views: 35594

Answers (2)

Nicky
Nicky

Reputation: 3827

Turns out I use gulp-htmlmin, which in turn uses html-minifier, where the default setting for camelCase attributes is set to false. Hence the updated error message saying routerlink instead of routerLink. Very subtle issue so hope this helps to anyone!

Upvotes: 0

Avnesh Shakya
Avnesh Shakya

Reputation: 3906

You can try like this:

<a [routerLink]="[ '/', 'contact' ]" routerLinkActive="active">Contact</a>

You can change first value of array [routerLink]="[ '..', 'contact' ]" based on your routing nested hierarchy. And add RouterModule into app.module.ts using imports:

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

Hope this will work for you.

Upvotes: 10

Related Questions