angular 2 rc5 template parse error

2019-06-06 20:06发布

问题:

I keep getting this error when I'm trying to create an angular routing link:

zone.js:461 Unhandled Promise rejection: Template parse errors:
Can't bind to 'routerLink' since it isn't a known property of 'a'. ("
</h1>
<button (click)="doLogin()">Login</button>
<a [ERROR ->][routerLink]="['/createservice']" href="#">Post a Service</a>
<router-outlet></router-outlet>
"): AppComponent@4:3 ; Zone: <root> ; Task: Promise.then ; Value: BaseExceptionconsoleError @ zone.js:461
zone.js:463 Error: Uncaught (in promise): Template parse errors:(…)

This is my code:

<a [routerLink]="['/createservice']" href="#">Post a Service</a>

and in my component I have this:

import { RouterLink } from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'app-root',
  providers: [AngularFire],
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  directives: [RouterLink]
})

I also tried this:

<a routerLink="/createservice" routerLinkActive="active">Post a Service</a>

following this tutorial (https://angular.io/docs/ts/latest/guide/router.html#!#router-link) and that doesn't work either.

This is how I am bootstrapping my app:

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(firebaseConfig),
    RouterModule,
    routing
  ],
  declarations: [ AppComponent, CreateServiceComponent ],
  providers: [ appRoutingProviders ],
  bootstrap: [ AppComponent,FIREBASE_PROVIDERS ]
})
export class MyAppModule {}

if (environment.production) {
  enableProdMode();
}

bootstrap(AppComponent, [
  FIREBASE_PROVIDERS,
  defaultFirebase(firebaseConfig),
  firebaseAuthConfig({
  provider: AuthProviders.Facebook,
  method: AuthMethods.Popup
})]);

回答1:

You don't need to include directives: [RouterLink], To use [routerLink]. It will be available via the setup you do via RouterModule.forRoot.

 @NgModule({
  ...
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(<route paths and configurations>)
   ],
   ....
 })

In any Feature Module, you have to explicitly import it by adding RouterModule.

Hope this helps!!