I've just created a new angular project using the Angular CLI and scaffolded a new route user in it using the following commands.
ng new myproj
cd myproj
ng g route user
And then I ran the Angular CLI server using ng serve
.
But I can't see the content of the login template when I access the page /login
unless I add a link to some route, i.e:
<a [routerLink]="['/user']">User Info</a>
When I add the line above, then the router-outlet
gets filled, but if I strip out this line, then the router-outlet
renders empty again.
What's happening here?
Does someone know why is this happening?
import { Component } from '@angular/core';
import { Routes, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router';
@Component({
moduleId: module.id,
selector: 'myproj-app',
templateUrl: 'myproj.component.html',
styleUrls: ['myproj.component.css'],
directives: [ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS]
})
@Routes([
{path: '/user', component: UserComponent}
])
export class MyprojAppComponent {
title = 'Main Component working!';
}
<h1>{{title}}</h1>
<router-outlet></router-outlet>
And the non-understandable workaround
<a [routerLink]="['/user']">User Info</a>
import { Component, OnInit } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app-user',
templateUrl: 'user.component.html',
styleUrls: ['user.component.css']
})
export class UserComponent implements OnInit {
constructor() {}
ngOnInit() {
}
}
<p>
It should be showing but it isn't!
</p>
That's a known issue in the new RC router.
Alternatively you can also do
export class MyprojAppComponent {
constructor(router:Router) {}
One of these workarounds is necessary to get the router invoked.
I struggled few hours with returned empty [routerLink]
. There was no error on console. I had to add <base href="/">
on header of index.html. It worked after that.
As Gunter said, this is a known bug with the current RC (here's one of several issues on it: https://github.com/angular/angular-cli/issues/989). The approach that the angular tutorial and many others are taking right now is to use @angular/router-deprecated
. Starting from just after ng new myproj
and ng g route user
, you'll need to do the following:
npm install --save @angular/router-deprecated
src/system-config.ts
, change @angular/router
to @angular/router-deprecated
in the barrels
array.src//app/myproj.component.ts
, change:
Routes
to RouteConfig
in the import
line'@angular/router'
to '@angular/router-deprecated'
in the import
line@Routes
to @RouteConfig
for the decoratorname: 'User'
to the RouteConfig
object for /user
Also, note that for links in the pre-RC router you do <a [routerLink]="['User']">User Info</a>
(i.e. reference the name
rather than the path
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With