【问题标题】:Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native propertyAngular2 异常:无法绑定到“routerLink”,因为它不是已知的本机属性
【发布时间】:2016-03-22 21:15:32
【问题描述】:

显然 Angular2 的 beta 版本比新版本更新,所以那里没有太多信息,但我正在尝试做一些我认为是相当基本的路由。

对来自https://angular.io 网站的快速启动代码和其他sn-ps 进行黑客攻击导致了以下文件结构:

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。但是,其中一个答案中的“工作示例”是基于预测试版代码的——它可能仍然有效,但我想知道为什么我创建的代码不起作用。

任何指点将不胜感激!

【问题讨论】:

  • 另一个问题有所不同:directives: [ROUTER_DIRECTIVES].
  • 即使使用 ROUTER_DIRECTIVES,我也会遇到同样的错误。 @Component({selector: "app"}) @View({templateUrl: "app.html", directives: [ROUTER_DIRECTIVES, RouterLink]})
  • 添加 directives: [ROUTER_DIRECTIVES] 并从 [router-link] 更改为 [routerLink] 我不再收到错误消息。
  • 我遇到了同样的错误(NG8002:无法绑定到“routerLink”,因为它不是“a”的已知属性)。创建组件时我没有使用 cli。我忘记在我的模块中添加组件声明。在声明数组中添加组件名称为我修复了它。

标签: angular


【解决方案1】:

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

ma​​in.ts

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

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);

您的代码丢失了

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

你不能使用像routerLinkrouter-outlet 这样的指令而不让你的组件知道它们。

虽然指令名称在 Angular2 中更改为区分大小写,但元素仍使用名称中的 -,例如 &lt;router-outlet&gt;,以与需要在自定义元素名称中使用 - 的 web 组件规范兼容.

全球注册

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

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

那么不再需要在每个组件中添加ROUTER_DIRECTIVES

【讨论】:

  • 是的,您也可以在启动应用程序时分配多个指令,如下所示:- provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES, FORM_DIRECTIVES, ETC...], multi: true})
  • 没错,但FORM_DIRECTIVES已经默认包含在PLATFORM_DIRECTIVES中了。
  • 这太好了,谢谢。在尝试将它们放在一起时,我还发现这很有用:stackoverflow.com/questions/34391790/…
  • 这里可能是个愚蠢的问题,但这里的 RC.1、RC.2 是什么?我用的是angular 2.1.2,是哪个RC?
  • @AlexanderMills 为什么老男人会吓到你?旧答案经过实战考验,因此非常值得信赖;p
【解决方案2】:

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

对于

也可以使用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},
])

【讨论】:

  • 我认为这不再适用(Angular 5)等
【解决方案3】:

一般来说,每当您收到类似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 元素的 property 绑定。但它随后发现routerLink 不是a 元素的本机属性,因此它抛出关于未知属性的异常。


我从来没有真正喜欢过ambiguity of the syntax。即,考虑

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

仅通过查看 HTML,我们无法判断 whatIsThis 是否为

  • something 的本机属性
  • 指令的属性选择器
  • something 的输入属性

我们必须知道在组件/指令的元数据中指定了哪些directives: [...],以便在心理上解释 HTML。而且当我们忘记将某些东西放入directives 数组时,我觉得这种歧义会让调试变得更加困难。

【讨论】:

    【解决方案4】:

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

    这是一个很小的差异,但足以触发错误。最难看的是,每次我复制和粘贴时,这个微小的差异一直在躲避我的注意。纯属偶然,我看到了这个小差异并解决了它。

    【讨论】:

    • 谢谢,您可以提到“routerlink”与“routerLink”之间大小写的区别。 Angular 2 期望“routerLink”存在,但发现“routerlink”
    • 谢谢,出于某种原因,一些教程使用了“router-link”,中间有破折号。但是 routerLink 是正确的版本。
    • 同样的情况发生在 webpack 和 html-minifier 中,但仅限于生产环境。将 caseSensitive: true 添加到 html-loader 选项请参阅:github.com/SamanthaAdrichem/webpack-3.9.1-splitted-config-an‌​gular 用于工作 angular 5 + webpack 3.9 配置
    【解决方案5】:

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

    我试过这个方法:

    在 HTML 中:

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

    在 TS 文件中:

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

    【讨论】:

      【解决方案6】:

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

      这是我的解决方案:

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

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

      【讨论】:

        【解决方案7】:

        对于那些在尝试运行测试时发现此问题的人,因为通过 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/

        【讨论】:

        • 这是一个很棒的收获!我的项目正常运行没有任何问题,我必须在spec 文件中添加它。谢谢@raykrow!
        • 确认也可以在 Angular 4 中工作。谢谢!
        • 这一定是接受的答案,接受的答案是错误的,因为在导入RouterModule时,需要调用forRoot来满足模块,然后你应该提供BASE_HREF和...
        • 您知道这对于 Angular 5+ 是否有所不同?我在几个单元测试中遇到了类似的错误Can't bind to 'active' since it isn't a known property of 'a'.,并导入了RouterTestingModule
        【解决方案8】:

        你的模块中有

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

        你必须导出模块 RouteModule

        示例:

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

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

        【讨论】:

          【解决方案9】:

          在我的例子中,我在 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 {
                  
               }
          

          【讨论】:

            【解决方案10】:

            我真的很感谢@raykrow 的回答,当有人只在测试文件中遇到这个问题时!那是我遇到的地方。

            由于使用另一种方法来做某事作为备份通常很有帮助,所以我想提一下这种也有效的技术(而不是导入 RouterTestingModule):

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

            (通常,在&lt;a&gt; 元素上使用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 的解决方案。

            【讨论】:

              【解决方案11】:

              如果您使用共享模块,只需将 RouterModule 添加到声明您的组件的 Module 中,不要忘记添加 &lt;router-outlet&gt;&lt;/router-outlet&gt;

              引用自这里RouterLink does not work

              【讨论】:

                【解决方案12】:

                如果在单元测试时遇到这个错误,请写这个。

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

                【讨论】:

                  猜你喜欢
                  • 2016-07-29
                  • 2017-06-21
                  • 2016-09-05
                  • 2016-04-11
                  • 2016-04-06
                  • 2017-02-05
                  • 2019-04-08
                  • 1970-01-01
                  相关资源
                  最近更新 更多