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

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

问题描述:

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

I'm using Angular 2 CLI and I created the component "MyComponent" with the ng generate component MyComponent. As far as I know I have to add the component to the directive key-value-pair of the @Component decorator, but the typescript compilation fails at this point, saying that:

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!';
}

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

I didn't touch the code of the generated component, but just in case:

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() {
  }

}

错误本身表明指令在 Component 中不存在,因为它已被弃用.试试下面显示的这段代码,

Error itself says that directives doesn't exist in Component as it has been deprecated. try this code shown below,

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] .