【发布时间】:2016-09-23 10:11:03
【问题描述】:
我是 Angular 2 的初学者,我想让我的第一个应用程序正常工作。我正在使用打字稿。 我有 app.component.ts,其中我向另一个名为 todos.component 的组件发出指令,但在编译时出现以下错误:
[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'.
我的代码是这样的:
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:";
}
没有指令,应用程序可以正常工作。 任何帮助,将不胜感激!
提前致谢!
【问题讨论】:
-
你不是以错误的方式创建指令吗?来自 Angular2 文档
import { Directive, ElementRef, Input, Renderer } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { constructor(el: ElementRef, renderer: Renderer) { renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'yellow'); } } -
如果您使用最新的 Angular final,
directives不再存在于@Component元数据中(因此出现错误)。如果您要关闭教程,则应尝试找到更新的教程。短时间内发生了很多变化,很多教程已经过时。我个人会去Angular documentation 并从那里开始。 -
同意@peeskillet,看看这个angular.io/docs/ts/latest/guide/attribute-directives.html。只是不要使用@Component 的
directives:,只添加到app.module.ts的declarations:。
标签: javascript angular typescript