我是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-[component-name]></app-[component-name]>一起工作。因此,如果你的组件名为mycomponent.component.ts:

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello {{name}}</h1>
    <h4>Something</h4>
    <app-mycomponent></app-mycomponent>
  `,

其他回答

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

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

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

import {map} from 'rxjs/operators';

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

检查组件内的所有导入。

希望它能帮助到别人。

转到tsconfig。json文件。把这段代码写在angularCompilerOption下:

 "angularCompilerOptions": {
     "fullTemplateTypeCheck": true,
     "strictInjectionParameters": true,
     **"enableIvy": false**
 }

在你的components.module.ts中,你应该像这样导入IonicModule 这样的:

import {IonicModule} from '@ionic/angular';

然后像这样导入IonicModule:

  imports: [
    CommonModule,
    IonicModule
  ],

所以你的components.module.ts会像这样:

import { CommonModule } from '@angular/common';
import {PostComponent} from './post/post.component'
import { IonicModule } from '@ionic/angular';

@NgModule({
  declarations: [PostComponent],
  imports: [
    CommonModule,
    IonicModule
  ],
  exports: [PostComponent]
})
export class ComponentsModule { }```

上述错误从Angular 9开始也会产生。 这本书提供了一个解决方案。

该警告建议使用CUSTOM_ELEMENTS_SCHEMA,但所讨论的元素不是Web组件。我们希望Angular直接忽略这些元素。因此,我们使用NO_ERRORS_SCHEMA,“允许任何元素上的任何属性的模式”。 向各自的.spec文件添加模式:[NO_ERRORS_SCHEMA]可以消除错误。

await TestBed.configureTestingModule({
  declarations: [MyComponent],
  schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();

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