javascript - Angular 2-komponentdirektiv fungerar inte


Jag är nybörjare på Angular 2 och jag vill få min första app att fungera. Jag använder TypeScript. Jag har app.component.ts där jag har gjort en direktiv till en annan komponent som heter todos.component men jag får följande fel vid kompilering:

[0] app/app.component.ts(7,3): error TS2345: Argument of type '{ moduleId: string; selector: string; directives: typeof TodosComponent[]; templateUrl: string; s ...' is not assignable to parameter of type 'Component'.
[0]   Object literal may only specify known properties, and 'directives' does not exist in type 'Component'.

Min kod ser ut så här:

index.html

<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <app-root>Loading...</app-root>
  </body>
</html>

app.component.ts

import { Component } from '@angular/core';
import {TodosComponent} from './todos/todos.component';

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

export class AppComponent {
    title: string = "Does it work?";
}

app.component.html:

<h1> Angular 2 application</h1>
{{title}}
<app-todos></app-todos>

todos.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  moduleId : module.id,
  selector: 'app-todos',
  template: '<h2>Todo List</h2>'
})

export class TodosComponent {
    title: string = "You have to do the following today:";    
}

Utan direktivet fungerar appen bra. All hjälp skulle uppskattas!

Tack i förväg!

Svar #1

I din app.component.ts definierar du directive: [TodosComponent]. Egenskapen directive har tagits bort i RC6 från @Component()-dekoreraren.

Lösningen på detta är att:

  1. skapa ett NgModule och
  2. deklarera TodosComponent inuti declarations: []-arrayen.

Se här för ett exempel på AppModule:

https://angular.io/docs/ts/latest/tutorial/toh-pt3.html

Svar #2

module.id lades till initialt när Angular2 var i beta-version. Eftersom det med den nya versionen och Angular CLI-stöd inte längre är nödvändigt att lägga till moduleId:module.id kan du ta bort det från .ts-filer.

Relaterade artiklar