无法使用打字稿向我的 angular 2 应用程序添加新组件
问题描述:
我使用的是 Angular 2 CLI,并使用 ng 生成组件 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() {
}
}
答
错误本身表明指令不存在于 组件,因为它已被弃用.试试下面显示的代码,
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 中删除 directives:[MyComponentComponent].