首页 文章

Angular2异常:'t bind to ' routerLink ' since it isn' t是已知的本机属性

提问于
浏览
213

显然,Angular2的测试版比新版更新,所以没有太多的信息,但我试图做我认为是一些相当基本的路由 .

使用来自https://angular.io网站的快速入门代码和其他代码段进行黑客攻击导致了以下文件结构:

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

随着文件填充如下:

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

boot.ts

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

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

我在这里发现了一个模糊的相关问题; router-link directives broken after upgrading to angular2.0.0-beta.0 . 但是,其中一个答案中的"working example"是基于pre-beta代码 - 这可能仍然有效,但我想知道为什么我创建的代码不起作用 .

任何指针都会感激不尽!

11 回答

  • 8

    >=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)];
    

    main.ts

    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组件规范兼容 .

    register globally

    要使 ROUTER_DIRECTIVES 全局可用,请将此提供程序添加到 bootstrap(...)

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

    然后不再需要为每个组件添加 ROUTER_DIRECTIVES .

  • 0

    对于在尝试运行测试时发现这一点的人,因为通过 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/

  • 3

    Word of caution when coding with 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>
    

    这是一个小差异,但足以触发错误 . 最丑陋的部分是,每次复制和粘贴时,这种小差异都会让我不再注意 . 凭借纯粹的机会,我看到了这个小小的差异并解决了它 .

  • 22

    For >= 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>
            `
    })
    

    For < V5

    也可以使用 RouterLink 作为 directives ie . 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},
    ])
    
  • 311

    通常,每当出现 Can't bind to 'xxx' since it isn't a known native property 之类的错误时,最可能的原因是忘记在 directives 元数据数组中指定组件或指令(或包含组件或指令的常量) . 这就是这种情况 .

    由于您未指定 RouterLink 或常量 ROUTER_DIRECTIVES - 其中contains the following

    export const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, 
      RouterLinkActive];
    
    • directives 数组中,然后当Angular解析时
    <a [routerLink]="['RoutingTest']">Routing Test</a>
    

    它不知道RouterLink directive(使用属性选择器 routerLink ) . 由于Angular确实知道 a 元素是什么,因此它假定 [routerLink]="..."a 元素的属性绑定 . 但它随后发现 routerLink 不是 a 元素的原生属性,因此它抛出了有关未知属性的异常 .


    我从来没有真正喜欢ambiguity of the syntax . 即,考虑一下

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

    只是通过查看HTML我们无法判断是否 whatIsThis

    • something 的原生 property

    • 指令的属性选择器

    • something 的输入属性

    我们必须知道在组件_845743的元数据中指定了哪些 directives: [...] 才能在心理上解释HTML . 当我们忘记将一些东西放入 directives 数组时,我觉得这种模糊性使得调试变得有点困难 .

  • 9

    你有你的模块

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

    你必须导出模块RouteModule

    例:

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

    能够访问导入此模块的所有人的功能 .

  • 1

    在我的情况下,我已经在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 {
    
     }
    
  • -5

    我已经尝试了上面提到的所有方法 . 但没有一种方法适用于我 . 最终我得到了上述问题的解决方案,它对我有用 .

    我试过这个方法:

    在Html中:

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

    在TS文件中:

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

    当一个人只在测试文件中出现这个问题时,我非常感谢@ 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的解决方案 .

  • 86

    如果您使用共享模块,只需将RouterModule添加到声明组件的模块中,并且不要忘记添加 <router-outlet></router-outlet>

    从这里引用RouterLink does not work

  • 7

    我的解决方案很简单 . 我正在使用[href]而不是[routerLink] . 我已经尝试了[routerLink]的所有解决方案 . 在我的情况下,它们都不起作用 .

    这是我的解决方案:

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

    然后在TS文件中写入 getPlanUrl 函数 .

相关问题