在Angular 6中封装ng2-table

Encapsulating ng2-table in Angular 6

这是一个新手问题,请耐心等待。我想抽象ng2-table将其包装在可重用的组件中。首先,我定义了一个模板:

table.comp.html

1
2
3
<ng-table [config]="config"
          [rows]="rows" [columns]="columns">
</ng-table>

然后,我定义了组件:

table.comp.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Component } from '@angular/core';

@Component({
  selector: 'my-table',
  templateUrl: 'table.comp.html',
  styles: []
})
export class TableComponent {
   
    columns:Array = [
            {title: 'Name', name: 'name'},
            {title: 'Id', name: 'id'},
            {title: 'Age', name: 'age'},
          ];

    config:any = {
                paging: true,
                sorting: {columns: this.columns}
              };

 
    rows = [ .. // rows will be populated here  // .. ]
 }

最后,我定义了一个模块来导入ng2-table:

table.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Ng2TableModule } from 'ng2-table/ng2-table';
import { TableComponent } from './table.comp';

@NgModule({
  declarations: [
      TableComponent
  ],
  imports: [
    BrowserModule,
    Ng2TableModule
  ],
  bootstrap: [TableComponent]
})
export class TableModule {}

要调用my-table,我将其导入以下模块:

1
2
3
4
5
6
7
8
9
10
11
@NgModule({
  declarations: [
    CallingComponent
  ],
  imports: [
    BrowserModule,
    TableModule
  ],
  bootstrap: [CallingComponent]
})
export class CallingModule {}

及相关组件:

1
2
3
4
5
@Component({
      selector: 'some-selector',
      template: '<my-table></my-table>'
    })
export class CallingComponent {}

我在浏览器控制台中收到以下错误:

'my-table' is not a known element:

...

如何解决此问题?


您需要导出组件以在其他模块中可用。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@NgModule({
  declarations: [
      TableComponent
  ],
  exports: [
     TableComponent   // <-- this was missing
  ],
  imports: [
    BrowserModule,
    Ng2TableModule
  ],
  bootstrap: [TableComponent]
})
export class TableModule {}