我正在与angular玩耍,但出现此错误:错误TypeError:无法读取未定义的属性“名称” 我的代码是
recipe-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Recipe } from '../recipe.model'
@Component({
selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html',
styleUrls: ['./recipe-list.component.css']
})
export class RecipeListComponent implements OnInit {
recipes: Recipe[] = [
new Recipe('Test', 'Test Code', 'https://cdn.pixabay.com/photo/2016/06/15/19/09/food-1459693_960_720.jpg'),
new Recipe('Test 2', 'Test Code', 'https://cdn.pixabay.com/photo/2016/06/15/19/09/food-1459693_960_720.jpg')
];
constructor() { }
ngOnInit() {
}
}
recipe-list.component.html
<div class="row">
<div class="div col-xs-12">
<button class="btn btn-success">New Recipe</button>
</div>
</div>
<hr>
<div class="row">
<div class="col-xs-12">
<app-recipe-item
*ngFor="let recipeEl of recipes"
[recipe]="recipeEl"></app-recipe-item>
</div>
</div>
<app-recipe-item></app-recipe-item>
recipe-item.compoent.html
<a href="#" class="list-group-item clearfix">
<div class="pull-left">
<h4 class="list-group-item-heading">{{ recipe.name }}</h4>
<p class="list-group-item-text">{{ recipe.description }}</p>
</div>
<span class="pull-right">
<img [src]="recipe.imagePath" alt="{{ recipe.name }}" class="img-responsive" style="max-height:50px">
</span>
</a>
recipe-item.component.ts
import {Component, Input, OnInit} from '@angular/core';
import {Recipe} from '../../recipe.model';
@Component({
selector: 'app-recipe-item',
templateUrl: './recipe-item.component.html',
styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {
@Input() recipe: Recipe;
constructor() {
console.log('Recipe is' + this.recipe);
}
ngOnInit() {
}
}
答案 0 :(得分:1)
您只需使用“安全导航操作符”即可解决此问题。
使用插值时,建议在不确定对象时使用?
(“安全导航”)。
<a href="#" class="list-group-item clearfix">
<div class="pull-left">
<h4 class="list-group-item-heading">{{ recipe?.name }}</h4>
<p class="list-group-item-text">{{ recipe?.description }}</p>
</div>
<span class="pull-right">
<img [src]="recipe.imagePath" [alt]="recipe.name" class="img-responsive" style="max-height:50px">
</span>
</a>
这将清除您的控制台问题,但是您可能需要在组件周围的*ngFor
中div
:
<div *ngFor="let recipeEl of recipes">
<app-recipe-item [recipe]="recipeEl"></app-recipe-item>
</div>
还有一个优点:在HTML标记中工作时,请勿使用插值,而应使用属性绑定。 (例如[alt]="recipe.name"
)
答案 1 :(得分:0)
我认为我已经破解了这种情况:在您的recipe-list
组件模板中,由于某种原因,您在末尾添加了<app-recipe-item></app-recipe-item>
,似乎有些残余代码。
该组件很可能抛出错误,因为没有提供任何输入值。这也说明了屏幕截图底部的空白元素。
删除该内容,即可解决您提到的控制台错误,并摆脱空元素。祝你好运!