Reputation: 73
I think I am doing everything right here.
Although the browser console shows the error "Cannot read property 'name' of undefined":
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
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.
Upvotes: 6
Reputation: 3362
Change it
[mediaItem]="'firstMediaItem'" ---> [mediaItem]="firstMediaItem"
After use like
<h1 *ngIf="mediaItem">{{mediaItem.name}}</h1>
Upvotes: 0
Reputation: 1909
Remove quotes "'firstMediaItem'"
just <my-media-component [mediaItem]="firstMediaItem"></my-media-component>
Upvotes: 2
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