0

I am doing the Tour of heroes tutorial. When I add the following piece of code to my heroes.component.ts file I get an error that says "Property 'selectedHero' has no initializer and is not definitely assigned in the constructor." What should i do so that I don't see this error anymore? Thank you in advance.

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

My heroes.component.ts file looks like this:

import {Hero} from '../hero';
import {HEROES} from '../mock-heroes';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit{


  heroes=HEROES;
  selectedHero:Hero;

  constructor() {}

  ngOnInit(): void {
  }

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

My heroes.component.html file looks like this:

<ul class="heroes">
    <li *ngFor= "let hero of heroes" (click)= "onSelect(hero)">
        <span class="badge">{{hero.id}}</span>{{hero.name}}
    </li>
</ul>

<h2>{{selectedHero.name | uppercase}} Details</h2>
<div><span>id:</span>{{selectedHero.id}}</div>
<div>
    <label>name:
        <input [(ngModel)]= "selectedHero.name" placeholder="name">
    </label>
</div>
Giannis
  • 1,790
  • 1
  • 11
  • 29

2 Answers2

0

your poblem is them missing if around the html elements which are showing the selectedHero. Try to wrap that in a ng-if as described in the example:

<div *ngIf="selectedHero">

  <h2>{{selectedHero.name | uppercase}} Details</h2>
  <div><span>id: </span>{{selectedHero.id}}</div>
  <div>
    <label>name:
      <input [(ngModel)]="selectedHero.name" placeholder="name"/>
    </label>
  </div>

</div>

The error already shows you the problem as the selected hero is not set and can not be shown on first view.

Hellmy
  • 76
  • 6
0

Try to initialise default state for selectedHero:

selectedHero:Hero = {
  id: 0,
  name: 'default'
};
Vasile Radeanu
  • 824
  • 5
  • 17