I have three very basic components: AppComponent
, AdminComponent
and LoginComponent
. Both AppComponent
and LoginComponent
show a link to AdminComponent
. AppComponent
contains the router-outlet
and all the routing configuration.
Now for some reason angular renders <a [routerLink]="['Admin']">Admin</a>
to <a href="/admin">Admin</a>
in AppComponent
just as expected. However, the exact same link in LoginComponent
is rendered to <a>Admin</a>
. What am I doing wrong?
Angular versions tried: 2.0.0-beta.8 and 2.0.0-beta.9.
app.component.ts
import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {AdminComponent} from './admin.component';
import {LoginComponent} from './login.component';
@Component({
selector: 'ww-app',
template: `
<a [routerLink]="['Admin']">Admin</a> // This link works as expected
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ path: '/login', component: LoginComponent, name: 'Login', useAsDefault: true },
{ path: '/admin', component: AdminComponent, name: 'Admin' }
])
export class AppComponent {
}
login.component.ts
import {Component} from 'angular2/core';
import {RouterLink} from 'angular2/router';
@Component({
selector: 'ww-login',
directives: [RouterLink],
template: `
<div>
<a [routerLink]="['Admin']">Admin</a> // Renders <a>Admin</a>
<div>login box </div>
</div>
`
})
export class LoginComponent {
}
Rendered HTML output
<ww-app>
<a href="/admin">Admin</a> <!-- link as expected (AppComponent)-->
<router-outlet></router-outlet>
<ww-login _ngcontent-nky-2="">
<div>
<a>Admin</a> <!-- href is missing here (LoginComponent)-->
<div>login box </div>
</div>
</ww-login>
</ww-app>
Update
Alright, I just stumpled upon a similar question on so Issue with routerLink directive. Looks like angular2-polyfill.js is the bad boy. See Thierry's modified plunkr where I removed the polyfill from index.html.
Follow up question:
angular2-polyfill declares itself as
Angular2 polyfill for Angular1
It might be stupid to ask, but do I really need it? Obviously it fixed a problem for me, but it gives me kind of a bad feeling as this is not Angular 1. The additional deprecation warnings don't help either...
I think your problem is that you are setting your directives as [RouterLink]
instead of [ROUTER_DIRECTIVES]
.
If you see the code, the RouterLink directive is for other tags different than <a>
. The router link directive that works with <a>
tags is the RouterLinkWithHref.
Take a look at the code in https://github.com/angular/angular/blob/master/modules/%40angular/router/src/directives/router_link.ts
@Directive({selector: ':not(a)[routerLink]'})
export class RouterLink { ... }
@Directive({selector: 'a[routerLink]'})
export class RouterLinkWithHref implements OnChanges, OnDestroy { ... }
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