基本上,ionic g component myComponent 会更新 app.module.ts 并在 app 文件夹中创建组件。
但是,如果您想要一种更优雅的方式来添加组件。步骤如下:
ionic g module components
将生成一个名为components 的模块文件夹。然后生成一堆组件:
ionic g component components/myComponent --export
ionic g component components/myComponent2 --export
ionic g component components/myComponent3 --export
ionic g component components/myComponent4 --export
components.module.ts 内部可以这样写:
...
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { MyComponentComponent } from './my-component/my-component.component';
import { MyComponentComponent2 } from './my-component2/my-component2.component';
import { MyComponentComponent3 } from './my-component3/my-component3.component';
import { MyComponentComponent4 } from './my-component4/my-component4.component';
@NgModule({
declarations: [
MyComponentComponent,
MyComponentComponent2,
MyComponentComponent3,
MyComponentComponent4
],
imports: [
CommonModule,
FormsModule,
IonicModule,
],
exports: [
MyComponentComponent,
MyComponentComponent2,
MyComponentComponent3,
MyComponentComponent4
]
})
export class ComponentsModule {}
然后确保将组件模块导入app.module.ts:
...
import { ComponentsModule } from './components/components.module';
...
@NgModule({
declarations: [AppComponent],
imports: [
...
ComponentsModule,
...
],
providers: [
...
],
bootstrap: [AppComponent]
})
export class AppModule {}
要测试组件,您需要重新创建一个页面或组件。
ionic g page testing
将组件模块导入您的测试组件/页面或(类似地导入您当前的主页):
...
import { ComponentsModule } from '../components/components.module';
...
@NgModule({
imports: [
...
ComponentsModule,
...
],
declarations: [TestingPage]
})
export class TestingPageModule {}
最后,只需使用组件选择器在测试页面中编写组件即可。例如
<app-my-component></app-my-component>
<app-my-component2></app-my-component2>
<app-my-component3></app-my-component3>
<app-my-component4></app-my-component4>
希望这可能会有所帮助。