【发布时间】:2018-09-23 16:03:28
【问题描述】:
当我这样做时:
ionic generate component my-component
创建了这个文件夹结构:
components
my-component
my-component.ts
my-component.scss
my-component.html
components.module.ts
我想在页面中使用这个组件。我不打算在 Ionic 3 中使用新的延迟加载机制,但我不介意。无论哪种方式最简单,我只想使用该组件!顺便说一句,我的页面本身没有模块,这是页面的文件夹结构:
pages
somepage
somepage.ts
somepage.scss
somepage.html
现在回到组件:我在模板中使用自定义离子组件(离子网格)。所以my-component.html 看起来像这样:
<ion-grid></ion-grid>
该行在 VS Code 中以红色突出显示。错误内容如下:
'ion-grid' is not a known element:
1. If 'ion-grid' is an Angular component, then verify that it is part of this module.
2. If 'ion-grid' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
这应该通过在components.module.ts 中添加IonicModule 和CommonModule 来解决一百个帖子和问题:
@NgModule({
declarations: [MyComponent],
imports: [
CommonModule ,
IonicModule
],
exports: [MyComponent]
})
export class ComponentsModule {}
但这当然不能解决错误。
第二个问题是页面无法识别新的自定义元素。这行在somepage.html:
<my-component></my-component>
也以红色突出显示并显示此错误:
'my-component' is not a known element:
1. If 'my-component' is an Angular component, then verify that it is part of this module.
2. If 'my-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
我最初虽然必须将组件模块添加到app.module.ts:
@NgModule({
declarations: [
MyApp,
SomePage
],
imports: [
...
ComponentsModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
SomePage
],
providers: [...]
})
export class AppModule {}
但这并没有解决任何问题。在阅读了大量帖子 2 小时后,我意识到可怕的 components.module.ts 是为了延迟加载,我必须为页面添加一个模块,所以我放弃并尝试将组件直接添加到 app.module.ts:
@NgModule({
declarations: [
MyApp,
SomePage,
MyComponent
],
imports: [
...
MyComponent
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
SomePage
],
providers: [...]
})
export class AppModule {}
我也尝试了其他组合,但没有任何效果。看在上帝的份上,这在 Angular 中是最简单的事情,在 Ionic 2 中也很容易。到底需要做什么才能在 Angular 3 中使用组件?
【问题讨论】:
-
你可以做一个样本,我们可以直接编辑它吗? + 你能给我们看看 component.ts 吗?
-
延迟加载是强制的吗?
-
@carton
components.ts显示在问题中。除了我添加了 IonicModule 和 CommonModule 之外,该文件与生成的完全相同。没用。 -
如果不是强制性的,那么只需删除
my-component.module.ts文件,并将您的组件导入app.module.ts文件。它会解决你的问题。 + 将此行添加到您的page.html。@ViewChild("my-component") my-component: MyComponentClass; -
my-component.ts 上方是否有“@IonicPage()”装饰器?
标签: angular typescript ionic-framework components ionic3