“无法使用@input在角度2中读取未定义的属性'name'

时间:2017-02-16 08:44:14

标签: angular typescript

我想我在这里做的一切。

虽然浏览器控制台显示错误“无法读取属性'名称'未定义”:

enter image description here

我的media.component.ts如下所示:

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看起来像:

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

app.component.html看起来像:

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

media.component.html看起来像:

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

4 个答案:

答案 0 :(得分:6)

当Angular尝试解析绑定时,使用安全导航操作符来防止再次设置mediaItem

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

<强>更新

在您的Plunker中,MediaAppComponent中列出了@NgModule({ bootstrap: [App, MediaAppComponent]}),但如果将此组件用作普通组件,则该组件不应该存在。只应在那里列出根组件。

Plunker example

答案 1 :(得分:2)

删除引号&#34;&#39; firstMediaItem&#39;&#34; 只是<my-media-component [mediaItem]="firstMediaItem"></my-media-component>

答案 2 :(得分:1)

使用elvis operator { "rules": { "customers": { ".read": "auth != null", ".write": "auth != null", "$CID": { "customerName": { ".validate": "newData.isString() && newData.val().length < 100" }, "customerCode": { //Code shouls be string, less than 4 characters and it can't be already stored on customerCode table for the current userId ".validate": "newData.isString() && newData.val().length<3 && !root.child('customerCode').child(auth.uid).exists()" }, "customerLimit": {} } } "customerCode": { "$CID": { "CustomerCodeId": { ".read": "auth != null", ".write": "auth != null", } } } } 代替

?

如果数据不存在,这将阻止angualr抛出任何错误,并允许数据异步显示

答案 3 :(得分:0)

改变它

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

使用后像

<h1 *ngIf="mediaItem">{{mediaItem.name}}</h1>
相关问题