简体   繁体   中英

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?

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

Here's the problem

<hero-detail [hero]="selectedHero"></hero-detail>

This puts "selectedHero" in "hero". So in the HTML I must use hero and not selectedHero

hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM