Я начинающий в угловой 2, и я хочу, чтобы мое первое приложение работало. Я использую TypeScript. У меня есть app.component.ts, в котором я сделал директиву другой compoent называется todos.component, но я получаю следующее сообщение об ошибке во время компиляции:Угловая директива 2-х компонентная не работает
[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.componen t.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:";
}
Без директивы, приложение работает отлично. Любая помощь будет оценена!
Заранее благодарен!
Вы не создаете директиву неправильно? из «Документации по угловому документу» {Директива, ElementRef, Input, Renderer} из '@ angular/core'; @Directive ({селектор: '[myHighlight]'}) экспорта класс HighlightDirective { конструктор (эл: ElementRef, рендерер: рендерер) { renderer.setElementStyle (el.nativeElement, 'BackgroundColor', 'желтого'); } } ' – Pradeepb
Если вы используете последнюю версию Angular final,' directives' больше не существует в метаданных '@ Component' (следовательно, ошибка). Если вы уходите из учебника, вы должны попытаться найти более новый. За короткий промежуток времени произошло много изменений, и много учебников устарели. Я лично хотел бы перейти к [Угловая документация] (https://angular.io/docs/ts/latest/) и начать с этого момента. –
Согласитесь с @peeskillet, посмотрите на этот https://angular.io/docs/ts/latest/guide/attribute-directives.html. Просто не используйте 'директивы:' @Component, добавьте его в 'declarations' 'app.module.ts'':. – haxpor