Search code examples
angularincludeangular-ng-if

Angular 4 "Heroes tutorial" bind issue with "templateUrl" and "NgIf"


I've been following the Angular 4 tutorial and I got here

https://angular.io/tutorial/toh-pt3

I followed all the steps faithfully, except for 1 thing: I really don't like to write HTML into JS or TS.

So my "Hero Detail" component should look like this:

@Component({
  selector: 'hero-detail',
  template: `
    <div *ngIf="hero">
      <h2>{{hero.name}} details!</h2>
      <div><label>id: </label>{{hero.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="hero.name" placeholder="name"/>
      </div>
    </div>
  `
})

But it looks like this:

@Component({
    selector: "hero-detail",
    templateUrl: "./templates/heroes_detail.html",
    styleUrls: ["./css/heroes_detail.css"]
})

Of course I created the matching HTML

<div *ngIf="selectedHero">
    <h2>{{selectedHero.name}} details!</h2>
    <div><label>id: </label>{{selectedHero.id}}</div>
    <div>
        <label>name: </label>
        <input [(ngModel)]="selectedHero.name" placeholder="name"/>
    </div>
</div>

THE ISSUE

The issue is that if I use "template" it works, but if I use "templateUrl" it doesn't!

Is there any issue like Angular1 with scope and ngIf?


Solution

  • You changed hero variable into selectedHero in your html file. Change it also in your component .ts file.