簡體   English   中英

Angular2 異常:無法綁定到“routerLink”,因為它不是已知的本機屬性

[英]Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

顯然 Angular2 的測試版比新的要新,所以沒有太多信息,但我正在嘗試做一些我認為相當基本的路由。

使用https://angular.io網站上的快速入門代碼和其他片段進行黑客攻擊,產生了以下文件結構:

angular-testapp/
    app/
        app.component.ts
        boot.ts
        routing-test.component.ts
    index.html

文件填充如下:

索引.html

<html>

  <head>
    <base href="/">
    <title>Angular 2 QuickStart</title>
    <link href="../css/bootstrap.css" rel="stylesheet">

    <!-- 1. Load libraries -->
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/angular2/bundles/router.dev.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>

  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>

</html>

啟動文件

import {bootstrap}    from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from 'angular2/router';

import {AppComponent} from './app.component'

bootstrap(AppComponent, [
    ROUTER_PROVIDERS
]);

app.component.ts

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';

import {RoutingTestComponent} from './routing-test.component';

@Component({
    selector: 'my-app',
    template: `
        <h1>Component Router</h1>
        <a [routerLink]="['RoutingTest']">Routing Test</a>
        <router-outlet></router-outlet>
        `
})

@RouteConfig([
    {path:'/routing-test', name: 'RoutingTest', component: RoutingTestComponent, useAsDefault: true},
])

export class AppComponent { }

路由-test.component.ts

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';

@Component({
    template: `
        <h2>Routing Test</h2>
        <p>Interesting stuff goes here!</p>
        `
})
export class RoutingTestComponent { }

嘗試運行此代碼會產生錯誤:

EXCEPTION: Template parse errors:
Can't bind to 'routerLink' since it isn't a known native property ("
        <h1>Component Router</h1>
        <a [ERROR ->][routerLink]="['RoutingTest']">Routing Test</a>
        <router-outlet></router-outlet>
        "): AppComponent@2:11

我在這里發現了一個模糊相關的問題; 升級到 angular2.0.0-beta.0 后路由器鏈接指令被破壞 但是,其中一個答案中的“工作示例”基於測試版前的代碼——它可能仍然有效,但我想知道為什么我創建的代碼不起作用。

任何指示將不勝感激!

>=RC.5

導入RouterModule另見https://angular.io/guide/router

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

>=RC.2

app.routes.ts

import { provideRouter, RouterConfig } from '@angular/router';

export const routes: RouterConfig = [
  ...
];

export const APP_ROUTER_PROVIDERS = [provideRouter(routes)];

主文件

import { bootstrap } from '@angular/platform-browser-dynamic';
import { APP_ROUTER_PROVIDERS } from './app.routes';

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);

<=RC.1

您的代碼丟失

  @Component({
    ...
    directives: [ROUTER_DIRECTIVES],
    ...)}

你不能在不讓你的組件知道它們的情況下使用像routerLinkrouter-outlet這樣的指令。

雖然在 Angular2 中指令名稱已更改為區分大小寫,但元素仍然使用-在名稱中,如<router-outlet>以與需要-在自定義元素名稱中的 web-components 規范兼容。

全局注冊

要使ROUTER_DIRECTIVES全局可用,請將此提供bootstrap(...)添加到bootstrap(...)

provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi: true})

那么就不再需要將ROUTER_DIRECTIVES添加到每個組件中。

對於在嘗試運行測試時發現這一點的人,因為通過npm testng test使用 Karma 或其他任何東西。 您的 .spec 模塊需要一個特殊的路由器測試導入才能構建。

import { RouterTestingModule } from '@angular/router/testing';

TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent],
});

http://www.kirjai.com/ng2-component-testing-routerlink-routeroutlet/

使用 Visual Studio 編碼時的注意事項 (2013)

我浪費了 4 到 5 個小時試圖調試這個錯誤。 我嘗試了我在 StackOverflow 上找到的所有解決方案,但仍然收到此錯誤: Can't bind to 'routerlink' since it isn't a known native property

請注意,當您復制/粘貼代碼時,Visual Studio 有自動格式化文本的壞習慣。 我總是從 VS13 得到一個小的瞬時調整(駱駝殼消失了)。

這個:

<div>
    <a [routerLink]="['/catalog']">Catalog</a>
    <a [routerLink]="['/summary']">Summary</a>
</div>

變成:

<div>
    <a [routerlink]="['/catalog']">Catalog</a>
    <a [routerlink]="['/summary']">Summary</a>
</div>

這是一個很小的差異,但足以觸發錯誤。 最丑陋的是,每次我復制和粘貼時,這種微小的差異都在躲避我的注意。 純粹是偶然,我看到了這個微小的差異並解決了它。

對於 >= V5

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
    {path:'routing-test', component: RoutingTestComponent}
];

@NgModule({
    imports: [
    RouterModule.forRoot(appRoutes)
    // other imports here
    ]
})

成分:

@Component({
    selector: 'my-app',
    template: `
        <h1>Component Router</h1>
        <a routerLink="/routing-test" routerLinkActive="active">Routing Test</a>
        <router-outlet></router-outlet>
        `
})

對於 < V5

也可以使用RouterLink作為directives即。 directives: [RouterLink] 這對我有用

import {Router, RouteParams, RouterLink} from 'angular2/router';

@Component({
    selector: 'my-app',
    directives: [RouterLink],
    template: `
        <h1>Component Router</h1>
        <a [routerLink]="['RoutingTest']">Routing Test</a>
        <router-outlet></router-outlet>
        `
})

@RouteConfig([
    {path:'/routing-test', name: 'RoutingTest', component: RoutingTestComponent, useAsDefault: true},
])

通常,每當您收到諸如Can't bind to 'xxx' since it isn't a known native property ,最可能的原因是忘記指定組件或指令(或包含該組件或指令)在directives元數據數組中。 這里就是這種情況。

由於您沒有指定RouterLink或常量ROUTER_DIRECTIVES – 其中包含以下內容

export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, 
  RouterLinkActive];

– 在directives數組中,然后在 Angular 解析時

<a [routerLink]="['RoutingTest']">Routing Test</a>

它不知道RouterLink 指令(它使用屬性選擇器routerLink )。 由於 Angular 確實知道a元素是什么,它假定[routerLink]="..."a元素的屬性綁定。 但隨后發現routerLink不是一個原生屬性a元素,因此它拋出關於未知財產除外。


我從來沒有真正喜歡過語法歧義 即,考慮

<something [whatIsThis]="..." ...>

僅通過查看 HTML 我們無法判斷whatIsThis

  • something的固有屬性
  • 指令的屬性選擇器
  • something的輸入屬性

我們必須知道哪些directives: [...]在組件/指令的元數據中指定,以便在心理上解釋 HTML。 當我們忘記將一些東西放入directives數組時,我覺得這種歧義會使調試變得有點困難。

你的模塊中有

import {Routes, RouterModule} from '@angular/router';

你必須導出模塊 RouteModule

例子:

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

能夠訪問所有導入此模塊的功能。

我已經嘗試了上面提到的所有方法。但是沒有一種方法適合我。最后我得到了上述問題的解決方案,它對我有用。

我試過這個方法:

在 HTML 中:

<li><a (click)= "aboutPageLoad()"  routerLinkActive="active">About</a></li>

在 TS 文件中:

aboutPageLoad() {
    this.router.navigate(['/about']);
}

就我而言,我已經在 App 模塊中導入了RouterModule ,但沒有在我的功能模塊中導入。 在我的 EventModule 中導入路由器模塊后,錯誤消失了。

    import {NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import {EventListComponent} from './EventList.Component';
    import {EventThumbnailComponent} from './EventThumbnail.Component';
    import { EventService } from './shared/Event.Service'
    import {ToastrService} from '../shared/toastr.service';
    import {EventDetailsComponent} from './event-details/event.details.component';
    import { RouterModule } from "@angular/router";
    @NgModule({
      imports:[BrowserModule,RouterModule],
      declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
      exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
       providers: [EventService,ToastrService]
    })
    export class EventModule {
        
     }

如果在單元測試時遇到這個錯誤,請寫這個。

import { RouterTestingModule } from '@angular/router/testing';
beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent],
  });
}));

我真的很感謝@raykrow 的回答,只有在測試文件中才有這個問題! 那是我遇到的地方。

因為用另一種方式做某事作為備份通常很有幫助,所以我想提一下這種也有效的技術(而不是導入RouterTestingModule ):

import { MockComponent } from 'ng2-mock-component';
. . .
TestBed.configureTestingModule({
  declarations: [
    MockComponent({
      selector: 'a',
      inputs: [ 'routerLink', 'routerLinkActiveOptions' ]
    }),
    . . .
  ]

(通常,人們會在<a>元素上使用routerLink ,但會相應地為其他組件調整選擇器。)

我想提到這個替代解決方案的第二個原因是,盡管它在許多規范文件中對我很有用,但在一種情況下我遇到了問題:

Error: Template parse errors:
    More than one component matched on this element.
    Make sure that only one component's selector can match a given element.
    Conflicting components: ButtonComponent,Mock

我不太清楚這個模擬和我的ButtonComponent是如何使用相同的選擇器的,所以尋找替代方法讓我在這里找到了 @raykrow 的解決方案。

如果您使用共享模塊,只需將 RouterModule 添加到聲明您的組件的模塊中,不要忘記添加<router-outlet></router-outlet>

從這里引用RouterLink 不起作用

我的解決方案很簡單。 我使用 [href] 而不是 [routerLink]。 我已經嘗試了 [routerLink] 的所有解決方案。 在我的情況下,它們都不起作用。

這是我的解決方案:

<a [href]="getPlanUrl()" target="_blank">My Plan Name</a>

然后在 TS 文件中寫入getPlanUrl函數。

暫無
暫無

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

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