I need to calculate which class belongs to every td in my table according to specific logic for every td. I also need to detect changes and update the class if the data changes.
What is the best practice to do it?
Example:
I have a cars signal data.
cars = toSignal(this.dataService.cars);
And I tried to write a computed like the following:
carStatus: Signal<StatusEnum> = computed(() => this.calcStatus());
This work fine to the first TD but I want to compute also the color (for example). Should I write more computed function to the color calculation?
And what if I have 10 rows in the table? How to calculate the class for every td in every row?
In such a case you should split the table row into a separate component which receives the row data via a signal input:
@Component({
selector: 'app-car',
template: `
<!-- other cells -->
<td>{{ carStatus() }}</td>
`,
styles: ':host { display: contents; }',
})
export class CarComponent {
car = input.required<YourCarModel>();
// Note that you need to read the `car` signal in this computed function, so Angular knows when to compute a new value
carStatus = computed(() => this.car().status);
color = computed(() => this.car().color);
}
It is totally fine to have multiple computed
functions in your component, it enables granular change detection which is the whole point of Angular signals.
In your existing component, the code should look somewhat like the following:
@Component({
template: `
<table>
<thead> <!-- header implementation --> </thead>
<tbody>
@for (car of cars(); track car.id) {
<tr><app-car [car]="car" /></tr>
}
</tbody>
</table>
`,
})
export class CarsComponent {
dataService = inject(DataService);
cars = toSignal(this.dataService.cars);
}