* ngIf具有动态变量Angular2

时间:2017-03-28 15:04:41

标签: angular angular-ng-if

我是angular2的新手! 我跟随这个例子:Angular2.io Example

selectedHero为null时,不应显示div元素,这样可以正常工作, 但是当我使用点击事件选择一个英雄时,selectedHero不为空 div元素仍未显示, 我也尝试过使用布尔变量,但是在更改click事件后,变量会更新,但div元素仍然没有显示。

  <ul>
    <li *ngFor='let hero of myHeroes' (click)="onSel(hero)">
      <div><label>id: </label>{{hero.id}}</div>
      <div><label>Name: </label>{{hero.name}}</div>
    </li>
  </ul>
</div>
<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>

这是组件代码:

export class AppComponent {
  title = 'Tour of heroes!';
  selectedHero: Hero;
  HeroesList: Hero[] = [//can also be used to display 
    { 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' }
  ];

  onSel(shero: Hero): void {
    this.selectedHero = shero;
    // alert(this.selectedHero.name);
  }
}

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

2 个答案:

答案 0 :(得分:1)

您遗漏了@angular/core的某些导入,其中ngIf已定义

请参阅plunk

ngIf无效的原因是创建的内容无效html。

答案 1 :(得分:0)

问题出在模板中,ul元素在div内,否则代码无效,让我知道原因,谢谢。

    <div>
      <ul>
        <li *ngFor='let hero of myHeroes' (click)="onSel(hero)">
          <div><label>id: </label>{{hero.id}}</div>
          <div><label>Name: </label>{{hero.name}}</div>
        </li>
      </ul>
    </div>

<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>