Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined":

https://i.sstatic.net/TvfEr.png

This is how my media.component.ts file is structured:

import { Component, Input } from '@angular/core';
@Component({
selector: 'my-media-component',
templateUrl: './app/media.component.html',
styleUrls: ['./app/media.component.css']
})
export class MediaAppComponent{
@Input() mediaItem;

onDelete(){
 console.log('deleting....');
}
}

And here's a look at my app.component.ts file:

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app/app.component.html',
 })
export class AppComponent  {
 firstMediaItem={
 name: 'sahil'
};
}

Let's not forget about app.component.html, which is very straightforward:

its, working
 <my-media-component [mediaItem]="firstMediaItem"></my-media-component>

The contents of media.component.html are minimal as well:

<h1>{{mediaItem.name}}</h1>

Answer №1

To ensure that Angular handles cases where mediaItem has not been set yet, make use of the safe-navigation operator:

<h1>{{mediaItem?.name}}</h1>

Additional Information

In your Plunker demo, you included MediaAppComponent in the

@NgModule({ bootstrap: [App, MediaAppComponent]})
declaration. However, if this component is meant to be a regular component and not a root one, it should not be listed there. Only root components should be included.

Check out the Plunker example

Answer №2

Take out the single quotes from 'firstMediaItem' before passing it to

<my-media-component [mediaItem]="firstMediaItem"></my-media-component>

Answer №3

Consider using the elvis operator ? in your code

<h1>{{mediaItem?.name}}</h1>

By using this approach, you can avoid Angular from throwing errors when data is missing and allow for asynchronous data display

Answer №4

Modify

[mediaItem]="'initialMediaItem'" ---> [mediaItem]="initialMediaItem"

Subsequently employ as

<h2 *ngIf="mediaItem">{{mediaItem.title}}</h2>

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

Utilizing NgModelGroup nesting in various components for improved data management

Whenever I attempt to nest NgModelGroup inside another NgModelGroup, Angular seems to just ignore it. I'm currently utilizing Angular 12 and Template-driven Forms. Here is how my code appears: app.component.html <form #form="ngForm"> ...

Sending data to templates in Angular 2 using @Input()

I can't seem to figure out what I'm doing wrong with my listing template. I am trying to make it more dynamic by passing parameters using []="" and @Input(). Here is an example: <div class="listing wrapper"> <div class="wrapper" ...

Is there a way to make sure that ngbpopovers stay open even when hovering over the popover content?

I have implemented a ngbpopover to display user information on an element. Currently, the popover is triggered on both hover and click events, but I would like it to remain open when hovered over, instead of closing as soon as the mouse moves away. How c ...

Universal Angular along with Window's Innerwidth

Utilizing Window.Innerwidth in my Angular Project has been successful, however, I encountered an issue when attempting to implement it into Angular Universal. The content within window.innerwidth does not appear in the view source. Here is a snippet of my ...

Removing outlines on <p> <a> or <div> elements with Ionic and Angular seems to be a challenging task

Hey there, I’m currently working on my application which includes a login page. I've implemented a “Forgotten password ?” link, but no matter what I try, like using .class and :focus {outline: none}, I still see a yellow square around the item. ...

Using ngFor to dynamically populate drop-down options from a key value object in Angular 2

How can I use ngFor in Angular 2 to dynamically populate options in dropdown menus from a key value object? Below is the JSON data: { "employment": { "0": "Employed", "2": "Un-employed", "3": "Retired", "4": "Self" "V ...

Is it impossible to use type as a generic in TypeScript?

Struggling with TypeScript in React and encountered an issue. I decided to use a generic to build an abstracted class related to Axios. However, I ran into an ESLint error when using any as the type parameter for my generic. ESLint: Unexpected any. Specif ...

Exploring the latest upgrades in React 18 with a focus on TypeScript integration

I am currently working on a complex TypeScript project with React and recently made the decision to upgrade to the new version of React 18. After running the following commands: npm install react@18 npm install react-dom@18 npm install @types/react-dom@18 ...

Create a sleek and innovative tree user interface in a single line with the power of Angular and fxF

I created a tree with parent and child nodes, but I'm facing an issue where the positions of the checkboxes are not aligned in a straight line. Here is my code snippet: <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle> ...

Cross-origin resource sharing problem (Backend developed in Express, Frontend in Angular)

I am currently utilizing Angular for my front-end development and Express for the back-end. I encountered a CORS issue with one of multiple API endpoints that have similar configurations: Failed to load http://localhost:3000/api/deletePost: No 'Acc ...

Storing various checkbox values into a database

I have a form with checkboxes that I need to submit to an API for database storage. This is the city.page.html <ion-item *ngFor="let city of cities;"> <ion-checkbox [(ngModel)]="city.id" ></ion-checkbox> <i ...

Pinia is having trouble importing the named export 'computed' from a non-ECMAScript module. Only the default export is accessible in this case

Having trouble using Pinia in Nuxt 2.15.8 and Vue 2.7.10 with Typescript. I've tried numerous methods and installed various dependencies, but nothing seems to work. After exhausting all options, I even had to restart my main folders on GitHub. The dep ...

Errors were encountered while parsing providers in SystemJS with angular2-in-memory-web-api

Having some trouble integrating angular2-in-memory-web-api into my project. Progress has been made, but now encountering (SystemJS) Provider parse errors: (...). Not sure what I'm missing, everything compiles fine and no 404 errors are showing up, so ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...

Exploring the ckeditor5-typing plugin within CKEditor

Currently, I am in the process of developing a soft keyboard using CKEditor. One part of this involves transforming text upon input (which I have completed) and occasionally needing to delete a key (where I am currently facing challenges). Below is the sni ...

Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario: let rangeOfInterest = [25 , 44]; let input = [10, 20, 30, 40, 50, 60]; I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the inpu ...

A Typescript object that matches types and eventually returns a string when called upon

In the process of overengineering a type that can match either a string or an object whose valueOf() function, when evaluated recursively, ultimately returns a string. type Stringable = string | StringableObject; interface StringableObject { valueOf() ...

Tips for configuring the _document.tsx file in Next.js for optimal performance

I found most of the code for this project in the official documentation example on utilizing styled-components: https://github.com/vercel/next.js/blob/canary/examples/with-styled-components/pages/_document.js However, the example was written in .js and I ...

Organizing Telephone Number Entries in Angular

In my search for a way to format a phone number input field in Angularjs, I have come across many solutions, but none specifically for Angular 7. What I am looking to achieve is for the user to enter the textfield like so: 123456789 and have the textfi ...

Angular 2 router hybrid application: URL resets after navigation

Each time a route is changed, the correct component is rendered but there seems to be an issue with the path. For example, when navigating from /items to /add-item, the URL changes momentarily but then reverts back. This issue occurs on every page, reg ...