Angular 10: Table row as a component, misalignment of table data

Viewed 792

I have this problem: I have a table that displays some cars and Edit/Delete buttons; I want every table row to be a car component. Instead of

<tr *ngFor="let car of filteredCars">
  <td> {{car.Brand }}
  ..
  <td> <button> Edit </button> </td>
  <td> <button> Delete </button> </td>
</tr>

I need to display the car properties using a car component. So I created my component as following:

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

@Component({
    selector: 'car-component',
    template: `
        <td> {{Brand}} </td>
        <td> {{Model}} </td>
        <td> {{Power}} </td>
    `
})
export class CarComponent { 
    @Input() CarId: number;
    @Input() Brand: string;
    @Input() Model: string;
    @Input() Power: string;
}

The problem is when I try to

 <tr *ngFor="let car of filteredCars">
 <car-component [CarId]="car.CarId" [Brand]="car.Brand" [Model]="car.Model" 
     [Power]="car.Power">
 </car-component>
//buttons
 </tr>

The content of the car component is displayed in the first data cell of the table row:

enter image description here

I understand that he takes the whole car component as the first , the problem is I can't manage to achieve the solution. I tried: using templates / directive.

1 Answers

First of all you don't need to make a component for just td. You can make a component with full tr like this

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

@Component({
  selector: 'car-component',
  template: `
   <tr>
    <td> {{carData.Brand}} </td>
    <td> {{arData.Model}} </td>
    <td> {{arData.CarId}} </td>
   </tr>
 `
 })
export class CarComponent { 
 @Input() carData: any;
}

and then you can use your car component like this

 <car-component [carData]="car" *ngFor="let car of filteredCars">
 </car-component>
Related