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

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

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

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