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

时间:2018-11-11 21:40:10

标签: angular typescript ionic-framework ionic4

我是Ionic的新手,我想创建一个自定义列表视图,其中包含可扩展项,其链接如下: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]
})

3 个答案:

答案 0 :(得分:1)

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

component.module

答案 1 :(得分:0)

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

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

通过

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

OR

或者您在ExpandableComponent

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

}

答案 2 :(得分:0)

在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

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