簡體   English   中英

Angular2:routeLink不會創建href屬性

[英]Angular2: routeLink does not create href attribute

我有三個非常基本的組件: AppComponentAdminComponentLoginComponent AppComponentLoginComponent顯示指向AdminComponent的鏈接。 AppComponent包含router-outlet和所有路由配置。

現在,由於某種原因使角<a [routerLink]="['Admin']">Admin</a><a href="/admin">Admin</a>AppComponent正如預期。 但是, LoginComponent的完全相同的鏈接將呈現給<a>Admin</a> 我究竟做錯了什么?

嘗試了Angular版本:2.0.0-beta.8和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 {
}

呈現HTML輸出

<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>

更新

好吧,我只是通過routerLink指令解決了類問題。 看起來像angular2-polyfill.js是壞孩子。 請參閱Thierry的修改過的plunkr ,我從index.html中刪除了polyfill

跟進問題

angular2-polyfill聲明為

用於Angular1的Angular2 polyfill

這可能是愚蠢的問題,但我真的需要嗎? 顯然它為我解決了一個問題,但它給我帶來了一種不好的感覺,因為這不是Angular 1.額外的棄用警告也無濟於事......

我認為您的問題是您將指令設置為[RouterLink]而不是[ROUTER_DIRECTIVES]

如果您看到代碼,則RouterLink指令適用於不同於<a>其他標記。 <a>標簽一起使用的路由器鏈接指令是RouterLinkWithHref。

看看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 { ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM