The `NgForOf` directive is used to iterate over lists of strings or string arrays within a given `NgIterable` of strings or string

Here is a data type example:

export interface TYPE_A {
  valueType: TYPE_A_VALUE_TYPES;
  value: string | string[];
}

export enum TYPE_A_VALUE_TYPES {
  singleValue = "singleValue",
  multiValue = "multiValue",
}

In my component, I am using TYPE_A for @Input:

@Input() inputData: TYPE_A[] = [];

This is how it's implemented in the HTML:

<div class="feildContainer" *ngFor="let input of inputData">
    <div class="singleFeild" *ngIf="input.valueType == 'singleValue'">
         ...
    </div>
    <div class="multiFeild" *ngIf="input.valueType == 'multiValue'">
        <other-component *ngFor="let valueData of input.value"></other-component>
    <div>
</div>

An error message appears in vscode:

NgForOf<string | string[], NgIterable<string | string[]>>.ngForOf: NgIterable<string | string[]> | null | undefined

Although I understand why this error occurs, I am seeking the optimal resolution.

Answer №1

To create a discriminated union for your type, follow these steps:

export interface TypeA_SingleValue {
  valueType: TypeA_ValueTypes.SingleValue;
  value: string;
}
export interface TypeA_MultiValue {
  valueType: TypeA_ValueTypes.MultiValue;
  value: string[];
}

export enum TypeA_ValueTypes {
  SingleValue = "SingleValue",
  MultiValue = "MultiValue",
}

When you need to access the value, ensure to first verify the valueType against the two possible values. The compiler will then understand whether you are referring to the single or multivalued item and interpret it accordingly. Following an if statement checking the valueType, the type of value will not be string | string[], but either string or string[] based on the condition.

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

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

Sending information between two Angular 7 applications

I have a challenge where I need to pass data between two Angular applications that are running on different domains. Despite my attempts to use window.postMessage, I am unable to successfully transfer data to the second application. The first application ...

Creating a versatile JavaScript/TypeScript library

My passion lies in creating small, user-friendly TypeScript libraries that can be easily shared among my projects and with the open-source community at large. However, one major obstacle stands in my way: Time and time again, I run into issues where an NP ...

Different methods to initiate multiple calls using the dispatch function within ngrx

Utilizing NGRX to dispatch the IDs from an array, I am facing the challenge of needing to make multiple simultaneous calls instead of looping through them in ngOninit. Here is the code snippet for dispatch: loadEmloyeePricing(): void { let id = []; ...

The Angular2 app and NodeJs in the Docker container are unresponsive

After creating a new Angular2 app using angular-cli and running it in Docker, I encountered an issue where I could not connect to it from localhost. First, I initialized the app on my local machine: ng new project && cd project && "put m ...

Upon installation of a new component, Angular components are automatically removed from the system

I am currently working on an asp.net core web application with angular 5 and I need to generate some Barcodes for printing. Fortunately, I came across ngx-barcode, which is a barcode component specifically designed for Angular4+. To install it, I used the ...

Save information for each session with a set expiration time

Currently, I am working on a mobile application using Angular (specifically Ionic 5) and I am in need of a solution to maintain session data for my users throughout their workflow. Initially, I thought about utilizing the sessionStorage feature for this p ...

The map() function's splice operation unexpectedly removes only half of the array

I am currently working with an array that contains 146 objects, each object having its own unique id. My goal is to delete any objects from the array that do not have a matching id. I wrote a function to accomplish this task, however, it only works for hal ...

Preserve Angular 2 service instances while navigating between routes

I am faced with a scenario where I have three components that are all utilizing the same DataService. This is not because they share the same data, but rather because they use the exact same methods and patterns: @Component({ templateUrl: './data ...

Implementing Observable lambdas in Angular templates for easy function calling

Within a component, I have the following code snippet: public hasFoo$: Observable<(name: string) => boolean> = ... Now, I would like to use this multiple times in my template with a stepper: <mat-vertical-stepper> <mat-step *ngIf="ha ...

I find that the value is consistently undefined whenever I attempt to set it within a promise in Angular

Hi there, I've encountered an issue with my getData() function in accountService.ts. I'm attempting to fetch user data and user account data simultaneously using a zip promise. Although the resolve works correctly and I receive the accurate data, ...

Invalid component prop provided to ButtonBase in Material UI. Ensure that the children prop is correctly rendered in this custom component

Forgive me for asking a basic question, as I am not the most proficient frontend developer and have searched extensively online. Whenever I inspect my frontend application in Chrome, I keep encountering this error. (3) Material-UI: The component prop pro ...

Navigating through an interface array using *ngFor in TypeScript

After successfully implementing an interface to retrieve data from a service class, I encountered an issue when attempting to iterate through the FilteredSubject interface array. Despite using console.log, I was unable to achieve the desired outcome. You ...

Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application. res=[ { "url": "/page1", "views": 2 }, { "url": "/page2", "views": 1 }, { "url": "/page1", "views": 10 }, { "url": "/page2", "views": 4 }, { "url": "/page3", "views": 1 }, ...

Is it possible to maintain the scroll position of a PrimeNG table when updating the data?

I've encountered a challenge while working on a project involving PrimeNG 12 tables with Angular 12. The issue lies in Angular's change detection mechanism and updating table data, specifically in preventing a PrimeNG p-table from scrolling back ...

Monitoring Unread Message Totals in Twilio Chat

Seeking an efficient method to retrieve and update the count of unread messages in Twilio chat. I have explored similar questions and answers on other platforms, such as this one, which suggested looping through the Channel's array and utilizing Messa ...

Transforming FormData string key names into a Json Object that is easily accessible

Recently, I encountered an issue where my frontend (JS) was sending a request to my backend (Node Typescript) using FormData, which included images. Here is an example of how the data was being sent: https://i.stack.imgur.com/5uARo.png Upon logging the r ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

The execution time of Node's Promises.all() function is unreasonably slow

I need to add a table containing data on sent emails after each email has been successfully sent. Within a loop, I am populating an array to be resolved using the Promise.all(). insertData is a function that adds data, requiring two parameters: connector, ...

The element does not recognize the property 'width' since it is not defined in the type of 'GlobalEventHandlers'

I'm trying to determine the size of an image using JavaScript, but I encountered a TypeScript error: const img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ ...