How can I efficiently display a list of various objects that inherit from the same abstract class in an Angular application? What is considered optimal practice for accomplishing this task?
Consider the following basic model:
abstract class Vehicle {
wheels: number;
}
class Car extends Vehicle {
isConvertible: boolean;
}
class Truck extends Vehicle {
freight: string;
}
Although my current approach does work, it seems rather inelegant and not entirely consistent with object-oriented programming principles.
Implementation in HTML Template:
<ul>
<li *ngFor="let vehicle of vehicles">
<p>{{vehicle.wheels}}</p>
<p *ngIf="isCar(vehicle)">{{asCar(vehicle).isConvertible}}</p>
<p *ngIf="isTruck(vehicle)">{{asTruck(vehicle).freight}}</p>
</li>
</ul>
Component Code:
@Component({
[...]
})
export class VehicleInfoComponent{
@Input() vehicles: Vehicles[];
public isCar(vehicle: Vehicle): boolean {
return vehicle instanceof Car;
}
public isTruck(vehicle: Vehicle): boolean {
return vehicle instanceof Truck;
}
public asCar(vehicle: Vehicle): Car{
return vehicle as Car;
}
public asTruck(vehicle: Vehicle): Truck{
return vehicle as Truck;
}
}
Is there a more elegant and object-oriented way to handle this scenario?