“无法读取未定义的属性'名称'";在角度2中使用@input [英] "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":
我的media.component.ts如下所示:
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....');
}
}
我的app.component.ts看起来像:
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看起来像:
app.component.html looks like:
its, working
<my-media-component [mediaItem]="firstMediaItem"></my-media-component>
media.component.html看起来像:
media.component.html looks like:
<h1>{{mediaItem.name}}</h1>
推荐答案
当Angular尝试解析绑定时,请使用安全导航运算符来保护尚未设置的 mediaItem
:
Use the safe-navigation operator to guard agains mediaItem
not yet being set when Angular tries to resolve the binding:
<h1>{{mediaItem?.name}}</h1>
更新
在您的Plunker中,您在 @NgModule({bootstrap:[App,MediaAppComponent]})
中列出了 MediaAppComponent
,但是如果使用了此组件,则不应存在该组件作为正常组件.应该只在其中列出根组件.
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.
这篇关于“无法读取未定义的属性'名称'";在角度2中使用@input的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!