Ionic 4 无法导入自定义组件不是已知元素

Ionic 4 cannot import custom component is not a know element

我是 Ionic 的新手,我想在 link : https://www.joshmorony.com/creating-an-accordion-list-in-ionic/ 之后创建一个带有可扩展项目的自定义列表视图。

问题是我的自定义组件从未被识别,我尝试了很多东西但没有任何效果...我正在使用 Ionic 4,他们在他们的文档中没有谈论组件生成。

错误是:

Error: Template parse errors:
'expandable' is not a known element:
1. If 'expandable' is an Angular component, then verify that it is part of this module.
2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

Here is my project folder

expandable.component.html :

<div #expandWrapper class='expand-wrapper' [class.collapsed]="!expanded">
    <ng-content></ng-content>
</div>

expandable.component.ts :

import { Component, Input, ViewChild, ElementRef, Renderer } from '@angular/core';

@Component({
  selector: 'app-expandable',
  templateUrl: './expandable.component.html',
  styleUrls: ['./expandable.component.scss']
})
export class ExpandableComponent {

  @ViewChild('expandWrapper', {read: ElementRef}) expandWrapper;
  @Input('expanded') expanded;
  @Input('expandHeight') expandHeight;

  constructor(public renderer: Renderer) {
  }

  ngAfterViewInit(){
      this.renderer.setElementStyle(this.expandWrapper.nativeElement, 'height', this.expandHeight + 'px');   
  }

}

下面是我尝试使用它的方式:

<expandable [expandHeight]="itemExpandHeight" [expanded]="pet.expanded">
      Hello people
</expandable>

最后,我的 app.module.ts :

@NgModule({
  declarations: [AppComponent, ExpandableComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(), 
    AppRoutingModule,
    IonicStorageModule.forRoot()
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    DatabaseService, 
    PetService,
    SQLite
  ],
  bootstrap: [AppComponent]
})

组件选择器的问题。您已经定义了选择器 app-expandable 但是您正在使用 expandable 替换下面的代码

<expandable [expandHeight]="itemExpandHeight" [expanded]="pet.expanded">
      Hello people
</expandable>

来自

<app-expandable [expandHeight]="itemExpandHeight" [expanded]="pet.expanded">
      Hello people
</app-expandable>

或者您在 ExpandableComponent

中更改选择器
@Component({
  selector: 'expandable', //<-- change here
  templateUrl: './expandable.component.html',
  styleUrls: ['./expandable.component.scss']
})
export class ExpandableComponent {

}

我找到了解决方案,您必须在组件的根目录下创建一个 component.module.ts,然后添加导入 ComponentsModule

component.module

在 Ionic 3 和 4 中,对我有帮助的是,记住仅添加

是不够的
import { ComponentsModule } from '../../components/components.module';

...
@NgModule({
  imports: [
    ...
    ComponentsModule,
    ...
  ],

给你的app.module.ts

您还需要将它添加到每个页面的模块中!

src/app/home/home.module.ts
src/app/about/about.module.ts
src/app/game/game.module.ts

我从来不喜欢在 NgModule 中使用 CUSTOM_ELEMENTS_SCHEMA ...