Leveraging interfaces with the logical OR operator

Imagine a scenario where we have a slider component with an Input that can accept either Products or Teasers.

public productsWithTeasers: (Product | Teaser)[];

When attempting to iterate through this array, an error is thrown in VS Code.

<div *ngFor="let product of productsWithTeasers"> {{ product.externalId }}</div>

Identifier 'externalId' is not defined. '<anonymous>' does not contain such a memberAngular

What is the correct approach to solving this issue?

Please note that the two objects are not alike, so using extend in interfaces is not desired in this case.

Answer №1

Consider enhancing the types within your productsWithTeasers. This adjustment resolved the issues I encountered in my VS Code.

productsWithTeasers: (Product | Teaser)[] | Product[] | Teaser[]
;

By defining it this way, the array can consist of a combination of Teasers and Products, or exclusively Teasers or Products.

For instance, here is a simple illustration: https://stackblitz.com/edit/angular-afcby5

html:

<div *ngFor="let prod of products">
  {{prod?.myProdAttribute}}
</div>

component:

@Component({
  selector: 'button-overview-example',
  templateUrl: 'button-overview-example.html',
  styleUrls: ['button-overview-example.css'],
})
export class ButtonOverviewExample {
  products: (Product | Teaser)[] | Product[] | Teaser[] = [{myProdAttribute: 'asd'},{myTeaserAttribute: 'fgdfg'}];
}

export class Product {
  myProdAttribute: string;
}

export class Teaser {
  myTeaserAttribute: string;
}

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

Problem Encountered in Angular 4 CLI when using enableProdMode in Internet Explorer 11

Currently, my Angular 4 application built using NodeJS works flawlessly on Internet Explorer 11 and the latest versions of Chrome and Firefox during development. However, when I enable Production Mode in the NodeJS Build as shown in the example from packa ...

Executing a designated assessment in Protractor

Is there a way to run a specific test scenario in my Angular app? I recently added a new feature in Protractor, created the necessary page and steps, but I already have other features implemented. I am wondering if it is possible to solely test the new f ...

Is it possible to transfer files using Angular 2?

Currently, I am utilizing Angular2 and TypeScript to transmit a file in conjunction with JSON Data to a designated server. HTML Code <input type="file" class="form-control" name="avatar" id="uploadyour" name="uploadyour" #uploadyour="ngModel" [(ngMode ...

Unable to bind click eventListener to dynamic HTML in Angular 12 module

I am facing an issue with click binding on dynamic HTML. I attempted using the setTimeout function, but the click event is not binding to the button. Additionally, I tried using template reference on the button and obtaining the value with @ViewChildren, h ...

typescript ways to exclude enum values

I am working with enums in TypeScript. enum Status { Cancelled = 'cancelled', Completed = 'completed', Created = 'created' } Now, I need to create another enum that includes only the values Completed and Created. enum S ...

Error message 'Chart was not disposed' is displayed in amChart while rendering live data through a socket connection

I encountered a similar issue with the amChart displaying a "chart was not disposed" warning, leading to memory leakage. To find a solution, I referred to the following guide: However, since I am updating the chart in real-time using socket connections a ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

I am having trouble getting bootstrap-icons to work in my Angular project and I'm eager to figure it out

I am having trouble incorporating bootstrap-icons into my angular project. Despite running the npm i bootstrap-icons command, I am unable to successfully add icons using icon fonts on my webpage. As a temporary solution, I have added the bootstrap icon CD ...

Using ngFor to loop through an array of objects and calculate the number of elements in an array property

Currently I am developing a web application using Angular 6. The data is obtained in the form of an array of objects from Firebase, and my intention is to present this information to the user by utilizing ngFor. export interface Competition { createdAt: ...

Sharing screen content in Firefox using Angular 6

I am developing an Angular application that requires screen sharing functionality. I am using adapter.js version 6.4.8 and testing it on Firefox Developer 64.0b11 & Firefox 63.0.3. Since browser implementations differ, my main goal is to make the applicati ...

Reorganize code in JavaScript and TypeScript files using VSCode

Is there a way to efficiently organize the code within a .js / .ts file using Vscode? Specifically, when working inside a Class, my goal is to have static variables at the top, followed by variables, then methods, and so on automatically. I did some resea ...

The dynamic fusion of Typescript and Angular 2 creates a powerful

private nodes = []; constructor(private nodeService: NodeService) {} this.nodeService.fetchNodes('APIEndpoint') .subscribe((data) => { this.nodes.push(data); }); console.log(this.nodes) This ...

The 'Element[]' type is lacking certain properties when dealing with react children

In my code, there is a parent component passing down its children to a child component. These children can be either single nodes or arrays of nodes, and the ChildComponent renders them differently based on their type. However, when I try to render the Chi ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

What is the reason the server is not receiving the cookie?

I am currently running a nodejs express application on a server with two endpoints: POST /session - used to send back the cookie GET /resource - used to check if the cookie is sent back, returning 401 not found if it's not On the frontend, hosted on ...

A guide on leveraging typeof within function parameters to ensure accurate variances

Let's create a simple class hierarchy and a list of instances. The goal is to filter items from the list of instances based on their class. There are a couple of challenges: We cannot use the typeof T syntax. How can this be written? We cannot decla ...

What causes the presence of undefined elements within the ngOnInit function of Angular?

When I initialize a library in my ngOnInit method like this: ngOnInit() { this.$grid = jQuery('.grid').masonry({ // options itemSelector: '.grid-item',//, columnWidth: 384, gutter: 24 }); ...... } and then call the method from ...

What is the mechanism behind the widening of object literal types in Typescript inference?

I've been reading up on how typescript broadens inferred types but I'm still not entirely clear about what's happening here: type Def = { 'T': { status: 5, data: {r: 'm'}}, } function route<S extends keyof Def> ...

Exploring the world of Angular's HttpClient Requests and Responses

As I delve into the world of signals, I find myself immersed in tutorials and articles on the topic. When it comes to calling an API endpoint using httpClient, I have come across two main approaches that caught my interest. Surprisingly, there isn't m ...

Connecting Ionic 3 with Android native code: A step-by-step guide

I just finished going through the tutorial on helpstack.io and was able to successfully set up the HelpStackExample with android native based on the instructions provided in the GitHub repository. The only issue is that my company project uses Ionic 3. H ...