无法使用打字稿向我的 angular 2 应用添加新组件

Can't add a new component to my angular 2 app with typescript

我正在使用 Angular 2 CLI,我使用 ng generate component MyComponent 创建了组件 "MyComponent"。据我所知,我必须将组件添加到 @Component 装饰器的指令键值对中,但是此时打字稿编译失败,说:

ERROR in [default] /Users/Philip/Desktop/Angular2/src/app/app.component.ts:8:2 
Argument of type '{ selector: string; template: any; styles: any[]; directives: typeof MyComponentComponent[]; }' is not assignable to parameter of type 'Component'.
  Object literal may only specify known properties, and 'directives' does not exist in type 'Component'.

这是我的应用代码:

import { Component } from '@angular/core';
import { MyComponentComponent } from './my-component/my-component.component'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  directives: [MyComponentComponent],
})
export class AppComponent {
  title = 'app works!';
}

我没有接触生成组件的代码,但以防万一:

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

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})

export class MyComponentComponent implements OnInit {

  constructor() {

  }

  ngOnInit() {
  }

}

错误本身说 指令不存在于 组件 中,因为它已被弃用。试试下面显示的代码,

import { MyComponentComponent } from './my-component/my-component.component'
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';

@NgModule({
   ...
   ...
   declarations:[AppComponent,MyComponentComponent], //<---need to declare 
   schemas:     [CUSTOM_ELEMENTS_SCHEMA]             //<---added this line
})

并从 AppComponent.

中删除 指令:[MyComponentComponent]

Angular2 组件装饰器不再使用这些来嵌入其他组件。我们需要使用一个名为 entryComponents 的新元数据来代替。请参阅下面的示例...

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  entryComponents:[VehicleListComponent]
})

车辆列表组件具有以下组件元数据..

@Component({
  selector: 'app-vehicle-list',
  templateUrl: './vehicle-list.component.html',
  styleUrls: ['./vehicle-list.component.css'],
  providers: [VehicleService]
})

如果您使用 Angular CLI,那么新组件将自动导入并添加到 app.module.ts 中 @ngmodule 的声明部分。我们不需要为此编写任何代码。

你有两个选择:

1: 在组件内部使用 entryComponents 标签

2: 使用 Angular CLI 自动导入它,所以我们不需要明确地为它编写代码。

在 运行 创建组件命令后,无需对 ANGULAR 4 或更高版本执行任何操作。该错误很可能只是您没有使用新组件元数据文件中的正确选择器名称(例如 componentname.component.ts)。