gpt4 book ai didi

javascript - Angular 4 : cannot read the property of undefined

转载 作者:行者123 更新时间:2023-12-03 03:10:59 25 4
gpt4 key购买 nike

我正在尝试通过他们在网站上提供的教程来学习 Angular4

这是代码

英雄.ts

export  class  Hero{

constructor(
public id: number,public name: string
){}
}

在 component.ts 中

import { Component } from '@angular/core';

import {Hero } from './hero';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent {


title : string;
hero : string;
selectedHero: Hero;

heroes = [
new Hero(1, 'Windstorm'),
new Hero(13, 'Bombasto'),
new Hero(15, 'Magneta'),
new Hero(20, 'Tornado')
]

myHero = this.heroes[0];

constructor(){
this.title = 'Tour of heros';

}

onSelect(hero: Hero): void {
this.selectedHero =hero;
}
}

html

<ul>
<li *ngFor="let hero of heroes" (click)="onSelect(hero)">
{{ hero.name }}
</li>
</ul>
<p>{{selectedHero.name}}</p>

当单击每个li时,我想显示所选对象中的详细信息,但出现以下错误

selectedHero.name 未定义

最佳答案

在访问其任何属性之前检查模板是否设置了 selectedHero

<p *ngIf="selectedHero">{{selectedHero.name}}</p>

或在组件中创建一个空实例(更新答案)

selectedHero: Hero = new Hero(12, 'somename');

关于javascript - Angular 4 : cannot read the property of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46953911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com