我想显示从Angular中的同一抽象类继承的不同对象的列表。有什么好的做法?
让我们假设以下简单模型:
abstract class Vehicle {
wheels: number;
}
class Car extends Vehicle {
isConvertible: boolean;
}
class Truck extends Vehicle {
freight: string;
}
我的方法可行,但是它看起来很丑陋,不是巧合。
HTML模板:
<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({
[...]
})
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;
}
}
还有更好的方法吗?
答案 0 :(得分:1)
我不知道它是否比你的好,或者它有什么好处。 尝试并按照自己的意愿去做。希望它是有用的。
@Component({
[...]
})
export class ActionInfoComponent{
@Input() vehicles: Vehicles[]
public getClass(vehicle: Vehicle): string{
return vehicle.constructor.name
}
}
和HTML
<ul>
<li *ngFor="let vehicle of vehicles">
<p>{{vehicle.wheels}}</p>
<p *ngIf="getClass(vehicle) == 'Car'">{{vehicle.isConvertible}}</p>
<p *ngIf="getClass(vehicle) == 'Truck'">{{vehicle.freight}}</p>
</li>
</ul>