error_handler.js:60 TypeError: Cannot read property 'name' of undefined at CompiledTemplate.prox

出现这个问题的原因是:你绑定的数据在应用启动的时候是undefined的,直接在模板中直接引用它的属性,浏览器当然就会挂掉了!

怎么解决呢?  只需要用*ngIf判断一下这个值是否有效,就可以了.

如下,这里我想做的是点击每一行li, 会在下方出现相对应的值,:

如我点击第一个li的时候,把它相对应的值数出来.显示如下:

html中: 

<div class="heroes-list">
<ul>
<li *ngFor = "let item of heroes" (click)="onSelect(item)" >
    {{item.id}}   {{item.name}}
</li>
</ul>
 <!-- 这样写会报错,应用运行的时候直接绑定,但是这个是触发事件后才给赋值  -->
<!-- <span>{{selectedHero.name}}</span> -->
<!--正确写法 -->
<span *ngIf="selectedHero">{{selectedHero.name}}</span>
</div>

ts中:

import { Hero } from './../hero';
import { Component, OnInit } from '@angular/core';
import {HEROES} from './mock-heroes';
import { parse } from 'querystring';
import { Jsonp } from '@angular/http';
@Component({
  selector: "app-heroes",
  templateUrl: "./heroes.component.html",
  styleUrls: ["./heroes.component.css"]
})
export class HeroesComponent implements OnInit {
  heroes = HEROES;
  selectedHero;
  onSelect(hero) {
    this.selectedHero = hero;
  };
  ngOnInit() {}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值