Jason Swett
Jason Swett

Reputation: 45174

Angular router 3 routerLink not working

I'm using Angular 2.0.0-rc3 with router 3.0.0-alpha.8.

I have a BookListComponent with the following template:

<nav>
  <a routerLink="/new-book">New Book</a>
</nav>

<ul>
  <li *ngFor="let book of books">{{ book.name }}</li>
</ul>

And then here's BookListComponent itself:

import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-book-list',
  templateUrl: 'book-list.component.html',
  styleUrls: ['book-list.component.css'],
  providers: [ROUTER_DIRECTIVES, BookService]
})
export class BookListComponent implements OnInit {
  books: any;

  constructor(private bookService: BookService) {}

  ngOnInit() {
    this.bookService.getList()
      .subscribe(response => this.books = response.json());
  }

}

Not only does the link not take me to the /new-book route (which, if visited "manually", works just fine), but the "link" isn't even a link - it's just black text.

How can I get the link to work?

Upvotes: 0

Views: 392

Answers (2)

Jason Swett
Jason Swett

Reputation: 45174

I have ROUTER_DIRECTIVES under providers but it needed to be under directives. Moving it to directives fixed the problem.

Here's my new BookListComponent:

import { Component, OnInit } from '@angular/core';
import { BookService } from '../book.service';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-book-list',
  templateUrl: 'book-list.component.html',
  styleUrls: ['book-list.component.css'],
  providers: [BookService],
  directives: [ROUTER_DIRECTIVES]
})
export class BookListComponent implements OnInit {
  books: any;

  constructor(private bookService: BookService) {}

  ngOnInit() {
    this.bookService.getList()
      .subscribe(response => this.books = response.json());
  }

}

Upvotes: 2

magiccrafter
magiccrafter

Reputation: 5482

Check if you are not missing the Router Outlet tag in the host's views HTML.

<router-outlet></router-outlet>

I use this as a reference:
https://angular.io/docs/ts/latest/guide/router.html

Upvotes: 0

Related Questions