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

3
  • 2
    Your selectedHero is undefined initially, thus the error. Commented Oct 26, 2017 at 12:08
  • so How do i initiaze? and one more thing what is this selectedHero: Hero declaration means?? Commented Oct 26, 2017 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: stackoverflow.com/a/39755385/7741865 Commented Oct 26, 2017 at 12:19

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

6 Comments

selectedHero: Hero = new Hero(); this declaration throws type expected error
Yes, that is because you have the constructor set up that you need to give the properties some intial value :)
I have updated my answer providing parameters to the constructor. It wasn't clear that they are 'required fields'.
@ChristianBenseler well if you look at the class, it has the properties in the constructor, so it's pretty clear ;)
It means that the type of selectedHero property is Hero. This is a typescript's feature.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.