简体   繁体   English

将 *ngIf 与 Angular 2 中的动态变量一起使用

[英]Using *ngIf with a dynamic variable in Angular 2

I was following this example : Angular2.io Example .我正在关注这个例子: Angular2.io Example

When selectedHero is null the div element should not be displayed, that works fine, but when I select a hero using click event and selectedHero is not null , the div element is still not displayed.selectedHeronull ,不应显示div元素,这可以正常工作,但是当我使用 click 事件选择一个英雄并且selectedHero不为nulldiv元素仍未显示。

I have tried using boolean variable too but after changing click event the variable is updated but the div element is still not displayed.我也尝试过使用boolean变量,但在更改单击事件后,变量已更新,但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>

This is the component code :这是组件代码:

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

You missing some imports from @angular/core where ngIf is defined您从定义了ngIf @angular/core中丢失了一些导入

see plunk看到plunk

The reason that ngIf is not working is that created content is not valid html. ngIf的原因是创建的内容不是有效的 html。

The problem was in template, ul element was to be within div , else the code was not working , let me know the reason for this, Thanks.问题出在模板中,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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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