Sahil Gupta
Sahil Gupta

Reputation: 73

"Cannot read property 'name' of undefined" in angular 2 using @input

I think I am doing everything right here.

Although the browser console shows the error "Cannot read property 'name' of undefined":

enter image description here

My media.component.ts looks like following:

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....');
}
}

My app.component.ts looks like:

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

app.component.html looks like:

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

media.component.html looks like:

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

Upvotes: 1

Views: 7163

Answers (4)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657148

Use the safe-navigation operator to guard agains mediaItem not yet being set when Angular tries to resolve the binding:

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

Update

In your Plunker you have MediaAppComponent listed in @NgModule({ bootstrap: [App, MediaAppComponent]}) but this component shouldn't be there if it is used as a normal component. Only root components should be listed there.

Plunker example

Upvotes: 6

yala ramesh
yala ramesh

Reputation: 3362

Change it

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

After use like

<h1 *ngIf="mediaItem">{{mediaItem.name}}</h1>

Upvotes: 0

Majesty
Majesty

Reputation: 1909

Remove quotes "'firstMediaItem'" just <my-media-component [mediaItem]="firstMediaItem"></my-media-component>

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86730

use elvis operator ? instead

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

this will prevent angualr to thorw any error if data is not present, and allow data to display asynchronously

Upvotes: 1

Related Questions