Pass an array of objects to an Angular 8 component for rendering

Recently, I started working with Angular 8 and faced an issue while trying to pass an array of objects to my component for displaying it in the UI.

parent-component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  options = [
    { key: "type", value: 'Type' },
    { key: "name", value: 'Name' },
    { key: "area", value: 'Area' }
  ]
  
  constructor() { }

  ngOnInit(): void {
   
  }
}

parent.component.html

<app-child [options]='options'></app-child>

child-component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() options: any[]
}

child.component.html

<div id="child-component>
    <select id="child-select">
        <option id="child-option-{{i}}" 
            *ngFor="let option of options | keyvalue; let i = index" 
            [value]="option.value"
        > Key: <b>{{option.key}}</b> and Value: <b>{{option.value}}</b> 
    </option>
    </select>
</div>

Currently, the output is:

  • Key: 0 Value: [object Object]
  • Key: 1 Value: [object Object]
  • Key: 2 Value: [object Object]

What I actually want to achieve is:

  • Key: type Value: Type
  • Key: name Value: Name
  • Key: area Value: Area

Although I tried using the pipe keyvalue, it didn't resolve the issue as expected.

If anyone has a solution or suggestion, I would greatly appreciate it. Thanks!

Answer №1

After removing the pipe keyvalue from the child component, my issue was successfully resolved. A big thanks to everyone for their help!

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

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

Tips for updating the checkbox state while iterating through the state data

In my component, I have the ability to select multiple checkboxes. When a checkbox is selected, a corresponding chip is generated to visually represent the selection. Each chip has a remove handler that should unselect the checkbox it represents. However, ...

Error: Azure AD B2C user login redirect URI is not valid

Currently working on setting up user login with Azure AD B2C. I have successfully created an App Registration in my B2C tenant and specified http://localhost:3000 as the redirect URI. However, when implementing it in my React app using the MSAL React libra ...

Alter the attributes of an instance in a class using a function

Attempting to explain a simple method in TypeScript. This method should allow modification of data for any object type within the data attribute. In simpler terms, we can modify, add, or remove data based on the specified data type, and TypeScript facilit ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

In the world of Typescript, object-based type inference reigns

I'm grappling with TypeScript to correctly deduce typing in the given code snippet: type Customer = { name: string } type Item = { price: number } const customerConfig = { action: () => [{name: 'Alice'}] as Customer[], } const item ...

MaterialUI Divider is designed to dynamically adjust based on the screen size. It appears horizontally on small screens and vertically on

I am currently using a MaterialUI divider that is set to be vertical on md and large screens. However, I want it to switch to being horizontal on xs and sm screens: <Divider orientation="vertical" variant="middle" flexItem /> I h ...

Gain insights on Stripe Webhooks with Firebase Functions and Node.js

I've been struggling to integrate Firebase functions with Stripe webhooks for listening to events. Take a look at my code: exports.stripeEvents = functions.https.onRequest((request, response) => { try { const stripeSignature = request. ...

Angular 14 is throwing an error due to an indent issue - the expected indentation is 2 spaces but 4 spaces were found

Currently using "eslint": "^8.23.0" with angular 14. Everything was functioning properly with "eslint": "^8.22.0", but after updating to 8.23.0, I encountered the following error: This is my eslint configuration: ...

Upgrading a Basic ReactJS Example to Typescript

Beginner Inquiry I recently converted a ReactJS script from Javascript to Typescript. Is there a more concise way to do this without relying heavily on "any" types? Original Javascript version: const App = ({title}) => ( <div>{title}</div& ...

The unexpected identifier 'express' was encountered in the import call, which requires either one or two arguments

I'm in the process of constructing an express server using typescript and Bun. Recently, I completed my register route: import express from "express"; const router = express.Router(); router.get('/registerUser',(_req:express.Reque ...

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Obtain a value that is not defined

Good day, I am encountering an issue with my data not accepting an undefined value. Below is the code snippet: interface IModalContatos { dados: IContatos; onSave(dados: IContatos): void; onClose(): void; } When passing this data to my modal, I rece ...

In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage. I am currently developing an Angular7 application. In one of my ...

React TypeScript: The properties of 'X' are not compatible. 'Y' cannot be assigned to 'Z' type

I am currently working on a React-TypeScript application, specifically creating a component for inputting credit card numbers. My goal is to have the FontAwesome icon inside the input update to reflect the brand image as the user enters their credit card n ...

Encountering an unexpected token error when using Typescript with Next

Currently, this is what I have in my _document.tsx file: import Document, { Html, Head, Main, NextScript } from 'next/document'; class CustomDocument extends Document { return = (): JSX.Element => ( <Html lang="en-US"> ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

How to process response in React using Typescript and Axios?

What is the proper way to set the result of a function in a State variable? const [car, setCars] = useState<ICars[]>([]); useEffect(() =>{ const data = fetchCars(params.cartyp); //The return type of this function is: Promise<AxiosRespo ...