在Angular中,组件可以属于两个声明的一部分。通常情况下,一个组件会在自己的组件类中声明,并在模板中使用。但是,有时候我们也需要在其他模块中声明组件,这样我们可以在不同的地方重复使用它。
以下是一个包含代码示例的解决方法:
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-custom-component',
template: 'Custom Component
',
})
export class CustomComponent {}
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CustomComponent } from './app.component';
@NgModule({
imports: [BrowserModule],
declarations: [CustomComponent],
bootstrap: [CustomComponent],
})
export class AppModule {}
// other.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomComponent } from './app.component';
@NgModule({
imports: [CommonModule],
declarations: [CustomComponent],
exports: [CustomComponent],
})
export class OtherModule {}
在上面的代码中,我们在OtherModule
模块中导入了CustomComponent
并将其声明为该模块的一部分。这样,我们就可以在OtherModule
模块的组件中使用CustomComponent
了。
希望这个解决方法能对你有所帮助!