无法使用打字稿向我的angular 2应用添加新组件 [英] Can't add a new component to my angular 2 app with typescript

查看:97
本文介绍了无法使用打字稿向我的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] .

这篇关于无法使用打字稿向我的angular 2应用添加新组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆