我是Angular2的新手。我试图创建一个组件,但显示一个错误。

这是app.component.ts文件。

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

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello {{name}}</h1>
    <h4>Something</h4>
    <my-component></my-component>
  `,
  directives: [MyComponentComponent]
})
export class AppComponent { name = 'Sam' }

这是我要创建的组件。

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

@Component({
selector: 'my-component',
template: `
    <p>This is my article</p>
`
})

export class MyComponentComponent {

}

显示两个错误:

如果my-component是一个Angular组件,那么验证它是否是这个模块的一部分。 如果my-component是Web组件,那么将CUSTOM_ELEMENTS_SCHEMA添加到@NgModule中。模式来抑制此消息。

请帮助。


当前回答

我有不同的模块除了app.module,例如主页。模块

我忘了把Home-page.component添加到Home-page。模块

其他回答

在我的例子中,我已经在其中生成了一个新模块和一个新组件,但是我还没有在component-name.module.ts中添加一些自定义编写的共享模块 文件和适当的路由配置应该添加到component-name.routing.module中。ts文件。检查其他组件的一致性。

这可能是html标签组件的名称

你可以在html中使用这样的东西<mycomponent></mycomponent>

你必须使用这个<app-mycomponent></app-mycomponent>

检查filename. ponent.ts中的选择器

在各种html文件中使用标签

<my-first-component></my-first-component>

应该是

<app-my-first-component></app-my-first-component>

例子

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

你是否像这样在app.module.ts中导入它并删除指令位:-

@NgModule({
    bootstrap: [AppComponent],
    imports: [MyComponentModule],// or whatever the name of the module is that declares your component.

    declarations: [AppComponent],
    providers: []
})
export class AppModule {}

你的MyComponentModule应该是这样的

@NgModule({
    imports: [],
    exports: [MyComponentComponent],
    declarations: [MyComponentComponent],
    providers: [],
})
export class MyComponentModule {
}

我有不同的模块除了app.module,例如主页。模块

我忘了把Home-page.component添加到Home-page。模块