在使用组件之前,必须先在模块中导入该组件。在导入组件时,请确保按照正确的文件路径和文件名进行导入。
示例:假设我们要在app.module.ts中使用my-component组件。在app.module.ts中导入my-component组件:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MyComponent } from './my-component/my-component.component';
@NgModule({ declarations: [ AppComponent, MyComponent ], imports: [ BrowserModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
在模块中导入组件之后,还需要在declarations中声明该组件。如果忘记声明该组件,就会导致组件在模块中无法识别。
示例:假如我们在app.module.ts中已经导入了my-component组件,但是忘记在declarations中声明该组件:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MyComponent } from './my-component/my-component.component';
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
在这种情况下,Angular会抛出“Component 'my-component' is not a known element”的错误信息。
如果一些组件是在独立的模块中定义的,那么在使用这些组件之前,必须确保这些模块已经被导入。
示例:假设我们的my-component组件是在my-component.module.ts中定义的。在app.module.ts中使用my-component组件之前,需要先导入my-component.module.ts:
import { NgModule