Angular 4 "Heroes tutorial" 与 "templateUrl" 和 "NgIf" 的绑定问题

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

我一直在学习 Angular 4 教程,现在我来到了这里

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

我忠实地遵循了所有步骤,除了一件事: 我真的不喜欢把HTML写成JS或者TS。

所以我的 "Hero Detail" 组件应该是这样的:

@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>
  `
})

但它看起来像这样:

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

当然是我创建了匹配项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>

问题

问题是,如果我使用 "template" 它可以工作,但是如果我使用 "templateUrl" 它就不行!

范围和 ngIf 是否存在类似 Angular1 的问题?

问题来了

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

这会将 "selectedHero" 放入 "hero"。 所以在 HTML 中我必须使用 hero 而不是 selectedHero

希望这对您有所帮助

您在 html 文件中将 hero 变量更改为 selectedHero。也在您的组件 .ts 文件中更改它。