Skip to content Skip to sidebar Skip to footer

My Own Angular 2 Table Component - 2 Way Data Binding

I see that support for datatables in angular 2 is very poor. DataTables does not work for me (known unresolved issue) so I thought that I will write something simple for myself. By

Solution 1:

update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

For your example creating a new component for row and col seems unnecessary.

With a simple filter pipe like

@Pipe({ name: 'filter' })
exportclassFilterPipeimplementsPipeTransform {
  transform(data: any[], filter:string) {
    console.log('filter', data, filter);
    if(!data || !filter) {
      return data;
    }
    return data.filter(row => row.some(col => col && col.indexOf(filter) >= 0));
  }
}

and a table component like

@Component({
    selector: 'my-table',
    template: `
<div style="width: 100%">
  <div style="float: left; height: 50px; width: 100%">
    Search: 
    <input type="text" 
        [(ngModel)]="filterValue" 
        name="filter"
        style="height: 30px; border: 1px solid silver"/> 
      {{filterValue}}
  </div>
  <div style="float: left; width: 100%">
    <table>
      <tr *ngFor="let row of data | filter:filterValue">
        <td *ngFor="let col of row let index=index">
          <template [ngTemplateOutlet]="templates && templates[index]" [ngOutletContext]="{$implicit: col}"></template>
        </td>
      </tr>
    </table>
  </div>
</div>
    `
})
exportclassMyTableComponent { 
  filterValue: string;
  @ContentChildren(TemplateRef) templateRefs:QueryList<TemplateRef>;
  @Input() data:any[];
  templates:TemplateRef[];

  ngAfterContentInit() {
    this.templates = this.templateRefs.toArray();
  }
} 

it can be used like

@Component({
  selector: 'my-app',
  template: `
<my-table [data]="data">
  <template let-col>1: {{col}}</template>
  <template let-col>2: {{col}}</template>
  <template let-col>3: {{col}}</template>
</my-table>
  `,
})
exportclassApp {
  data = [
    ['apple', 'orange', 'banana'],
    ['cat', 'dog', 'bird'],
    ['car', 'bicycle', 'airplane'],
  ];
}

where row and column data is passed to an input and the layout for the cells passed as <template> elements (one for each column - some additional checks are probably useful like checking if the number of templates is >= the number of columns in data).

Solution 2:

Actually it is quite easy to integrate DataTabes directly without using third party wrapper. Typings are already available in npm. It gives you opportunity to gradually extend your wrapper with required features.

Post a Comment for "My Own Angular 2 Table Component - 2 Way Data Binding"