Isetty Ravitejakumar Isetty Ravitejakumar - 26 days ago 15
Javascript Question

How to reuse the table component in angular2?

Iam new to Angular2 framework. Iam trying to reuse a single table component throughout my application. when, iam trying to do it ,iam facing difficulties to repeat any kind of array in my table row . How can i make my table row to iterate any kind of array which is passed as input to my table component.

Is it possible to reuse my table component when i pass array as an input to it??

Please help me. Following is my code snippet. How can i reuse it? Please suggest me the best approach to be done.

app.component.html

<table>
<thead>
<td>name</td>
<td>empid</td>
</thead>
<tbody>
<tr *ngFor="let item of items;">
<td>{{item.name}}</td>
<td>{{item.empid}}</td>
</tr>
</tbody>
</table>


app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
items=[{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"}];
}

Answer

yes you can make your tables as reusable table component:

table.component.ts

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

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent {
  @Input() items;
  @Input() field1;
  @Input() field2;

  constructor() {
  }

}

table.component.html

<table>
  <thead>
  <td>name</td>
  <td>empid</td>
  </thead>
  <tbody>
  <tr *ngFor="let item of items;">
    <td>{{item[field1]}}</td>
    <td>{{item[field2]}}</td>
  </tr>
  </tbody>
</table>

app.component.html

<app-table [items]="data" [field1]="field1" [field2]="field2"></app-table>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

    export class AppComponent{
           // data: any[] = [{name: "ravi", empid: "10215"}, {name: "ravi", empid: "10215"}];
  // field1: string = 'name';
  // field2: string = 'empid';

  field1: string = 'product';
  field2: string = 'price';
  data = [
    {product: "mobile", price: "10215"},
    {product: "camera", price: "10215"}
  ];



      constructor() { }

      ngOnInit() {
      }

    }
Comments