[英]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.