I am trying to learn angular4 with the tutorial they provided in website
Here is the code
hero.ts
export class Hero{
constructor(
public id: number,public name: string
){}
}
in 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>
when click on each li i would like to display details in selected object but i got the following error
selectedHero.name is undefined
selectedHeroisundefinedinitially, thus the error.selectedHero: Herodeclaration means??selectedHerois of yourHeroclass. You can use*ngIf="selectedHero"like from answer, or use{{selectedHero?.name}}or initialize your hero with some default from your array;ngOnInit() { this.selectedHero = this.heroes[0]}or initialize yourselectedHeroas a new hero:selectedHero = new Hero(null, '')or use one-way-binding together withngModelChange, example of the last option: stackoverflow.com/a/39755385/7741865