What is the best way to showcase a collection of inherited objects in Angular?

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?

Answer №1

It's hard to say if this is better than your solution or if it's even effective. Feel free to give it a try and see if it suits your needs. Hopefully, you find it helpful.

@Component({
    [...]
})
export class ActionInfoComponent{

    @Input() vehicles: Vehicles[]

    public getClass(vehicle: Vehicle): string{
         return vehicle.constructor.name
    }
}

and for the HTML part:

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the dropdown menu title dynamically based on the selection made in Angular

My Angular web-application has a dropdown menu that looks like this: <div class="btn-group" dropdown> <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">NAMEOFDROPDOWN <span class="caret"></span>&l ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

Generic Typescript Placeholder Design

Imagine you have the following data: const dataA = { name: "John", age: 25, attributes: {specificA: "hello", specificA2: 14, nonspecific:"Well"}, } const dataB = { name: "Lisa", age: 38, attributes: {spe ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Dealing with Angular State Management Across Components (Direct Dependency): encountering a NullInjectorError - R3InjectorError

I have encountered a NullInjectorError in my Angular application and I am seeking assistance in resolving it. To provide context, my application consists of three main components: ProductRegistrationAndListingScreen, ProductList, and ProductRegistration. ...

The JSX Configuration in TypeScript: Comparing ReactJSX and React

When working with Typescript and React, it's necessary to specify the jsx option in the compilerOptions section of the tsconfig.json file. Available values for this option include preserve, react, react-native, and react-jsx. { "compilerOptions": { ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...

Is it possible to integrate ngx Pagination with Bootstrap?

Is it possible to integrate Bootstrap's pagination with ngx Pagination? I'm interested in using the functionality of ngx Pagination but styling it with the CSS from Bootstrap. ...

JavaScript heap runs out of memory in Angular testing because of extensive mock data

While working on testing in angular 4, I encountered a need for large amounts of data in my test cases. Specifically, I needed to dynamically require JSON files in my spec files, each ranging from approximately 4 to 5 MB. As part of the process... it(& ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

What steps do I need to take for the function to accurately determine the return type?

class Foo { name: string; constructor({name}: {name: string}) { this.name = name; } } class Bar<T extends Foo> { foo: T; constructor({foo}: {foo: T}) { this.foo = foo; } } class CustomFoo extends Foo { xxx: string; constr ...

Add the component view to the webpage's body section

Using Angular 7 and ngx-bootstrap 4.0.1 Dependencies: "bootstrap": "3.3.7", "bootstrap-colorpicker": "2.5.1", "bootstrap-duallistbox": "3.0.6", "bootstrap-markdown": "2.10.0", "bootstrap-progressbar": "0.9.0", "bootstrap-slider": "9.8.0", "bootstrap-tags ...

Testing React Components - The `useClient` function should only be used within the `WagmiConfig` component

In my Next.js app with TypeScript, Jest, and React testing library, I encountered an error while trying to test a component. The error message states that `useClient` must be used within `WagmiConfig`. This issue arises because the `useAccount` hook relies ...

Having trouble installing Angular CLI on a Windows system with the latest version of npm

I am encountering an issue while attempting to install Angular CLI on my Windows 7 system through the command prompt using npm. The error message I receive is: D:\Users\uname>npm install -g @angular/cli npm ERR! code ELOOP npm ERR! sysca ...

Angular seed appears to experience a hiccup when the "Loading..." screen persists after the incorporation of a router-outlet

When working on a new Angular seed application using ng new, I encountered an issue where the application would get stuck at "Loading..." after adding the following to app.component.html: <router-outlet></router-outlet> In an attempt to resol ...

Step-by-step guide to setting up a TypeScript project on Ubuntu 15 using the

As a newcomer to UBUNTU, I have recently ventured into learning AngularJS2. However, when attempting to install typescript using the command: NPM install -g typescript I encountered the following error message: view image description here ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

Issue encountered: Dealing with a deadlock error triggered by a single query following the

I have a question about managing a query that runs across multiple micro-services, which can sometimes lead to deadlocks. const handleExecution = async (id: number): Promise<boolean> => { try { const query = ` UPDATE articles a1 ...

Upon being redirected to a different route, it immediately navigates back to the previous page

Whenever we redirect to a route using an anchor tag with [routerLink], or through the code using: router.navigate(['/path']) For example, if we redirect to the extractedData page from the result page, it initially shows the extractedData page b ...