[英]Ionic 4 (Angular 7) - sharing components issue
我正在尝试为像 Angular 这样的框架做一件非常平常的事情。 目标是通过共享模块多次使用相同的 ( HeaderComponent ) 组件。
我的 shared.module.ts:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { HeaderComponent } from '../header/header.component';
import { IonicModule} from '@ionic/angular';
@NgModule({
imports: [
CommonModule,
IonicModule
],
declarations: [
HeaderComponent
],
exports: [
HeaderComponent
]
})
export class SharedModule {}
在 app.module.ts 我添加了这个:
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, SharedModule],
在 home.page.html 中,我尝试以这种方式呈现它:
<app-header></app-header>
它实际上有效,因为浏览器向我显示了类似的错误
'ion-col' 不是已知元素
对于HeaderComponent 中的所有离子组件,依此类推。
我已经找到了问题在该建议增加互联网的解决方案IonicModule.forRoot(HeaderComponent)
到shared.module.ts的进口阵列,但这种方法会导致以下错误:
'app-header' 不是已知元素
好像已经不能用了。
您还必须像这样将 ionic 模块添加到您的共享模块中:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { HeaderComponent } from '../header/header.component';
import { IonicModule } from 'ionic-angular';
@NgModule({
imports: [
CommonModule,
IonicModule
],
declarations: [
HeaderComponent
],
exports: [
HeaderComponent
]
})
export class SharedModule {}
如果您使用 ionic 4,则必须将 IonicModule 的导入编辑为:
import { IonicModule } from '@ionic/angular';
在我的情况下,问题是我试图在一个用模态打开的组件中包含一个自定义组件。 我需要将我的组件添加到父页面的模块中。
我在尝试创建第三个(即共享模块)时遇到了很多问题,所以我发现这非常有帮助: https : //forum.ionicframework.com/t/ionic-4-create-shared-component-up-to-请日期示例/176887
我没有遵循关于摆脱东西的部分,但我确实在我的组件中添加了一个模块(在同一文件夹中)。 然后在其他页面中,我能够在顶部导入这个模块,然后在导入数组中,并且工作正常。
最终我不得不导入其他东西,比如上面加里所说的,但这只是常识。
我在网上找到的大多数教程都要求您创建另一个组件,然后使用该组件附带的模块。 遵循这种思路,我感到非常困惑。 我认为它基本上归结为,您可以共享模块,但不能共享组件。 不要引用我,但这就是我现在的理解。
头文件.component.html
<ion-header>
...
</ion-header>
header.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { feedService } from "../services/feed.service";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {
...
constructor() {}
ngOnInit() {}
}
头文件.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { HeaderComponent } from "./header.component";
@NgModule({
imports: [
...
],
declarations: [HeaderComponent],
exports: [HeaderComponent],
})
export class HeaderModule{
}
最后在该页面的 module.ts 中的其他地方使用它
import ... //other modules
import { HeaderModule } from "../header/header.module"; //your relative path
@NgModule({
imports: [
//other modules
HeaderModule,
],
declarations: [],
entryComponents: [],
})
export class MyPageModule {}
然后在该页面的 html 文件中,我可以使用上面 header.component.ts 中声明的选择器。
<app-header ...></app-header>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.