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":

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

The Angular 2 project, built with the CLI tool, has been transformed into an npm

We have a project in the works that involves creating a large application using angular 2. This project consists of one main parent angular 2 application and three separate sub-child applications that are unrelated to each other. Each of these sub-child ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

The ListItemButton's onclick event does not trigger on the initial click when utilizing a custom component as its children

I am having trouble comprehending why this onclick function is influenced by the children and how it operates <ListItemButton onClick={() => onClickResult(q)}> <Typography variant="body1">{highlighted}</Typography> ...

Using conditional styles with Angular 2

I am currently working on applying conditional styles to a table. For instance, if a user's "obsolete" property is true, I want to display their information with a <del> tag. I have searched online for solutions, and while I am aware of using *n ...

Navigating within Custom Web Component Angular

Recently, I attempted to create a custom web component using Angular ngDoBootstrap() { const el = createCustomElement(ServicemainComponent, { injector:this.injector }); customElements.define('servicemain', el); } After building the component in ...

How to remove the footer on a particular webpage

I am currently using angular version 14. On a specific page, there is a footer visible that I wish to hide. This page pertains to job search, and I would like to remove or conceal the footer specifically from this job search page. The footer has been separ ...

Having trouble getting the Angular Route to work, any tips on how to fix it?

I am currently learning Angular and have encountered a small issue. When I place the Component in my app.component.html as shown below, it functions correctly: <body> <div class="container"> <app-search-books></app-search-books ...

I'm having trouble figuring out how to access response headers with HttpClient in Angular 5. Can anyone

I recently developed an authentication service in Angular 5, where I utilize the HttpClient class to make a POST request to my backend server. The backend server then responds with a JWT bearer token. Here is a snippet of how my request looks: return thi ...

Understanding the significance of emitDecoratorMetadata in transpiled code

I have a question regarding the significance of the emitDecoratorMetadata option when transpiling TypeScript to JavaScript in an Angular 2 environment. If this option is set to false, and metadata is not included in the final code, what impact will it ha ...

Tips on integrating Ionic 2 with Angular 2 services

I'm a beginner with Ionic 2. I came across information in the Angular 2 documentation stating that services need to be injected during application bootstrapping. However, I didn't see any mention of bootstrapping while following the Ionic 2 tuto ...

TypeScript code runs smoothly on local environment, however encounters issues when deployed to production

<div> <div style="text-align:center"> <button class="btnClass">{{ submitButtonCaption }}</button> <button type="button" style="margin-left:15px;" class="cancelButton" (click)="clearSearch()"> {{ clearButtonCapt ...

What is the recommended approach for testing a different branch of a return guard using jest?

My code testing tool, Jest, is indicating that I have only covered 50% of the branches in my return statement test. How can I go about testing the alternate branches? The code snippet below defines a function called getClient. It returns a collection h ...

Modifying the color of a div element solely through CSS styling

I am currently working with a set of buttons, available at this link. While browsing through this helpful post, I encountered an issue. Whenever I click on another element, the orange color of my button disappears. How can I maintain the orange color on t ...

Reverse row changes in Angular Ag-Grid with the click of a button

Developed using Angular and JavaScript technologies. The AG-Grid consists of editable records with the first column being a checkbox. When changes are made to any selected records, clicking on a particular record's checkbox and then pressing a button ...

The Material Table in Angular is having issues with sorting functionality

I tried implementing the basic example from the angular material website, which displays a table with accurate data but the sorting functionality is not working as expected. For reference, you can view the StackBlitz demo here: https://stackblitz.com/edit ...

Setting up systemjs.config.js for utilizing relative paths within IIS - A step-by-step guide

My new ASP.NET MVC web application utilizes Angular for its UI components. I have set up the necessary config files in my project (e.g. package.json and systemjs.config.js). Created a test page Index.cshtml to test out the template in app.component.ts. The ...

Angular 6 experiencing issues with passing data into shared functions

I have developed a universal method for checking menu access in a service module named 'AuthService'. It communicates with the DataService class to retrieve relevant data. The common menu access function is supposed to be included in all componen ...

Using ReactJS with Material UI and applying styles with withStyles including themes in TypeScript

I've been working on converting the Material UI Dashboard into TypeScript. You can find the original code here: Material UI Dashboard One issue I'm encountering is that I am unable to define CSS styles within the withStyles function while export ...

There was an error encountered during the npm install process

C:\Users\Mayur Saner\pmrm>npm install npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to http://registry.npmjs.org/@fortawesome%2ffontawesome-free failed, reason: getaddrinfo ENOTFOUND proxy.company.com npm ERR! ...

Leveraging the power of LocalStorage in Ionic 2

Trying to collect data from two text fields and store it using LocalStorage has proven tricky. Below is the code I have set up, but unfortunately it's not functioning as expected. Can you provide guidance on how to resolve this issue? In page1.html ...