Render JSON value as an input in an Angular component using @Input()

In my app.component.html file, I have included the following template:

<test [someInput]="data"></test>

The 'data' variable is a JSON object property structured like this:

let data = {hello: "ciao"}

Below is the code from my test.component.ts file:

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

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {


  @Input()
  someInput:string

  constructor() { }


  ngOnInit() {

  }

}

This is the template found in my test.component.html file:

<p>{{someInput.hello}}, test is functioning as expected!</p>

I believe that 'someInput' will be replaced with the name of the JSON property 'data', and my browser should display "ciao". However, I am unsure of where to define the variable 'let data = {hello:ciao}'. When I place it in the .ts file, Chrome console returns an error:

TestComponent.html:1 ERROR TypeError: Cannot read property 'hello' of undefined
    at Object.eval [as updateRenderer] (TestComponent.html:1)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:45294)
    at checkAndUpdateView (core.js:44277)
    at callViewAction (core.js:44637)
    at execComponentViewsAction (core.js:44565)
    at checkAndUpdateView (core.js:44278)
    at callViewAction (core.js:44637)
    at execComponentViewsAction (core.js:44565)
    at checkAndUpdateView (core.js:44278)
    at callWithDebugContext (core.js:45632)

Answer №1

If you want to pass a value as an @Input, you must do it within the HTML of the PARENT COMPONENT (the component that is utilizing your test.component).

The code should resemble this

<! -- include some html here -->
<app-test [someInput]="helloData">

parent.component.ts

export class ParentComponent {
  helloData = {hello: 'ciao'}

  constructor() {}
}

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

Tips on accessing fields for union types that are passed to a function in TypeScript

I'm currently diving into the world of TypeScript, teaching myself by putting my newfound knowledge into practice. Below is the code I'm working on, but I've hit a roadblock trying to access the fields of the type passed to the function. C ...

Creating a Two-Way Binding Input Field in Angular to Display 'Invalid Date' Message if Incorrect Date is Selected in Datepicker

I am using an input field with an angular datepicker that is two-way bound to my model, which is of type string. The datepicker formats the existing date in DD/MM/YYYY format after converting it to toISOString(). However, if a non-existent date is entere ...

I want to modify a class in Angular 8 by selecting an element using its ID and adjust the styling of a div

Is it possible to dynamically add and remove classes using getElementById in Angular 8? I need to switch from 'col-md-12' to 'col-md-6' when a user clicks on the details icon. I also want to modify the style of another div by setting d ...

Establish a connection between MongoDB and the built-in API in Next.js

I've been working on integrating a MongoDB database with the Next.js built-in API by using the code snippet below, which I found online. /api/blogs/[slug].ts import type { NextApiRequest, NextApiResponse } from 'next' import { connectToData ...

When using `ng lint --fix=true`, the linting errors remain unresolved and are not fixed

Upon initializing a fresh project using "ng new" and adjusting tslint.json to utilize tabs instead of spaces, I encountered an issue where running "ng lint --fix=true" did not result in any changes to the .ts files: https://i.sstatic.net/yPJu2.png ng lint ...

Sending an HTTP POST request from an Angular 6 application utilizing Sendgrid and a NodeJs Google Cloud Function results in a Error 405 message

Attempting to access an Email through Sendgrid from an Angular 6 application with minimal payload. Utilizing a Google Cloud Function for the request leads to a 405 error from the browser: 405 Blocked by CORS policy: Response to preflight request doesn&ap ...

Tips for concealing or revealing an existing element with *ngfor

I am currently facing an issue with hiding and showing an element in Angular 4. This is the HTML code I am working with: <div class='row'> <div class='col-md-4 imgTxt' *ngFor="let path of imagePaths" > <img [id] ...

Can the child component ensure that the Context value is not null?

In the process of developing a Next.js/React application with TypeScript, I've implemented a UserContext in pages/_app.js that supplies a user: User | null object to all child components. Additionally, there's a ProtectedRoute component designed ...

What is the most effective way to determine the data type of a variable?

My search skills may have failed me in finding the answer to this question, so any guidance towards relevant documentation would be appreciated! I am currently working on enabling strict type checking in an existing TypeScript project. One issue I'v ...

How to fix the TS4090 error regarding conflicting definitions for a node in Visual Studio 2017

My TypeScript project is building and running, but I'm encountering a multitude of build errors all originating from one issue: TS4090: (TS) Conflicting definitions for 'node' found at 'C:/[projectpath]/node_modules/@types/node/index ...

Enhancing class functionality with decorators in TypeScript

Over on the TypeScript's Decorator reference page, there is a code snippet showcasing how to override a constructor with a class decorator: function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) { return class extends con ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

How can I prevent the enter key from working with Twitter Typeahead?

Is there a way to prevent the enter key from being pressed on an element within Twitter Typeahead's dropdown feature while using Angular with Typescript? I attempted to utilize preventDefault() when event.keycode === 13 on the ng-keydown event for th ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

The Bootstrap modal I implemented is opening correctly, but for some reason, the form inside is not appearing

I created the AddJokeModalComponent to streamline the process of opening a form without duplicating code in every component. Below is the modal structure: <ng-template #addJokeModal> <div class="modal-content my-custom-modal"> ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

Whenever I try to update my list of products, I encounter an error message stating that the property 'title' cannot be read because it is null

I am encountering an issue with editing data stored in the database. When attempting to edit the data, it is not displaying correctly and I am receiving a "cannot read property" error. HTML admin-products.component.html <p> <a routerLink="/ad ...

Pass a string with quotation marks to a component input in Angular 6

Need help with passing a string input to a component: @Component({ selector: 'abcComponent' template: ` <div> .... </div>` }) export class AbcComponent { @Input() text:string; } I am trying to send a strin ...

What is the best way to programmatically define the value for the MaterialUI grid size property using TypeScript?

Is there a way to dynamically pass a value to the Grid size props like XL in TypeScript? For instance, *Update for further clarification import Grid, { GridSize } from "@material-ui/core/Grid"; let value: GridSize = 12/4; xl={value} Error: Type &apos ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...