gpt4 book ai didi

angular - ionic 3 : How to add a component

转载 作者:太空狗 更新时间:2023-10-29 17:22:47 25 4
gpt4 key购买 nike

当我这样做时:

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

现在回到组件:我在模板中使用自定义 ionic 组件 (ion-grid)。所以 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.

这应该根据一百个帖子和问题解决,方法是将 IonicModuleCommonModule 添加到 components.module.ts 中:

@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 中使用组件?

最佳答案

我终于解决了这两个问题。

问题 #1:如何让应用程序识别组件:

  1. 删除components.module.ts。下次生成组件时,使用阻止 ionic 再次创建此文件的标志:

    ionic 生成组件 mycomponent --no-module

  2. 手动将组件添加到 app.module.ts 中,仅在 declarations 中:

    @NgModule({
    declarations: [
    MyApp,
    SomePage,
    MyComponent
    ],
    ...
    })
    export class AppModule {}
  3. 现在您可以在任何页面模板中使用它。

问题 #2:如何在组件模板中使用 Ionic 组件:

您不需要做任何特别的事情。只需使用它们。在将组件添加到 app.module.ts 之前,我遇到了一些错误,并且 Visual Studio Code 没有从“问题”选项卡中删除错误。但该应用程序有效。我刚刚重新启动 VS Code,错误不再出现。显然这是 VS Code 的一个已知问题,您需要重新启动它以消除旧错误。

关于angular - ionic 3 : How to add a component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com