【问题标题】:Trying the Master/Detail of Angular2 Tutorial尝试 Angular2 教程的大师/细节
【发布时间】:2017-04-29 18:52:49
【问题描述】:

我按照官方教程一步一步学习Angular2。我总是完全按照它的指示做,但我无法通过 ngFor 指令获取英雄列表。所以,这是我的代码:

app.component.ts

import { Component } from '@angular/core';

export class Hero {
  id: number;
  name: string;
};

const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Tour of Heroes';
  hero = HEROES;
};

app.template.ts

<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
  <label>name: </label>
  <input [(ngModel)]="hero.name" placeholder="name">
</div>

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span>
    {{hero.name}}
  </li>
</ul>

浏览器结果

这里是教程:https://angular.io/docs/ts/latest/tutorial/toh-pt2.html 现在?那有什么问题?只是第一步!谢谢你的帮助。

【问题讨论】:

  • 嘿!你能创建一个代码sn-p,这样我们就可以看到所有的部分了吗?
  • heroes = HEROES; 而不是 hero = HEROES
  • 你试图在一个组件的模板中显示 hero.name 和 hero.id,这个组件没有一个英雄,但是有一个英雄数组。这没有多大意义。
  • 在教程中我看到selectedHero: Hero;
  • 你遗漏了一些细节,没有双关语的意思 - 只是更接近地引用这个例子 - angular.io/resources/live-examples/toh-2/ts/eplnkr.html

标签: angular


【解决方案1】:

当您执行“让英雄中的英雄”时,hero 是为您和您迭代的变量。但是需要在组件中声明英雄。是您引用的用于迭代的数组。它是区分大小写的,所以事实是你没有声明英雄,你已经声明了英雄。

【讨论】:

    【解决方案2】:

    我终于明白了,错误就在这里:

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

    变量hero.namehero.id 在您选择列表中的英雄之前不会被声明。因此,如果您按照官方教程进行操作,请注意这一点,因为他们说它必须起作用,但在您使用选择功能完成代码之前不会这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 2019-08-17
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      相关资源
      最近更新 更多