0

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

Jabaa
  • 1,743
  • 7
  • 31
  • 60
  • 2
    Your `selectedHero` is `undefined` initially, thus the error. – AT82 Oct 26 '17 at 12:08
  • so How do i initiaze? and one more thing what is this `selectedHero: Hero` declaration means?? – Jabaa Oct 26 '17 at 12:09
  • declaration just means, that your variable `selectedHero` is of your `Hero` class. 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 your `selectedHero` as a new hero: `selectedHero = new Hero(null, '')` or use one-way-binding together with `ngModelChange`, example of the last option: https://stackoverflow.com/a/39755385/7741865 – AT82 Oct 26 '17 at 12:19

1 Answers1

1

Check in the template if selectedHero is set before access any of its property

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

or create an empty instance in the component (updated answer)

selectedHero: Hero = new Hero(12, 'somename');
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71