我是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中。模式来抑制此消息。

请帮助。


当前回答

检查父组件在哪个模块中被声明…

如果父组件定义在共享模块中,那么子模块也必须定义在共享模块中。

父组件可以在共享模块中声明,而不是在基于文件目录结构/命名的逻辑模块中声明,即使在我的例子中,Angular CLI也将它添加到错误的模块中。

其他回答

你的MyComponentComponent应该在MyComponentModule中。

在MyComponentModule中,你应该把MyComponentComponent放在“exports”中。

类似的代码,请参见下面的代码。

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

export class MyComponentModule {
}

并像这样将MyComponentModule放在app.module.ts的导入中(参见下面的代码)。

import { MyComponentModule } from 'your/file/path';

@NgModule({
   imports: [MyComponentModule]
   declarations: [AppComponent],
   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule {}

这样做之后,组件的选择器现在可以被应用程序识别。

你可以在这里了解更多信息:https://angular-2-training-book.rangle.io/handout/modules/feature-modules.html

检查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']
})

在我的例子中,我正在为一个使用子组件的组件编写单元测试,并且我正在编写测试以确保这些子组件在模板中:

it('should include the interview selection subview', () => {
    expect(fixture.debugElement.query(By.css('app-interview')))
    .toBeTruthy()  
  }); 

我没有得到一个错误,但一个警告:

警告:“应用面试”不是一个已知的元素: 如果'app-interview'是一个Angular组件,那么验证它是这个模块的一部分。警告:“应用面试”不是一个已知的元素: 如果'app-interview'是一个Angular组件,那么验证它是这个模块的一部分。 如果'app-interview'是一个Web组件,那么将'CUSTOM_ELEMENTS_SCHEMA'添加到'@NgModule '中。这个组件的模式 为了压制这条信息。”

此外,在测试期间,子组件没有在浏览器中显示。

我使用ng g c newcomponent来生成所有的组件,所以它们已经在appmodule中声明了,而不是我正在指定的组件的测试模块。

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ EditorComponent,
        InterviewComponent]
    })
    .compileComponents();
  }));

在我的例子中,我在Shared模块中有一个组件。

组件正在加载并且工作良好,但typescript用红线突出显示html标记,并显示此错误消息。

在这个组件中,我注意到我没有导入rxjs操作符。

import {map} from 'rxjs/operators';

当我添加这个导入时,错误消息消失了。

检查组件内的所有导入。

希望它能帮助到别人。

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