找不到显示元素并将其添加到angular2中的列表中

时间:2017-01-15 07:54:56

标签: angular angular-ng-if

在我的英雄应用程序中,我有一个输入文本,检查服务是否存在英雄。如果存在,则以下拉列表显示。 我想要的是显示英雄名称(如果不存在),还添加一个按钮以将英雄添加到数组中。

我的hero-search.component.html

<div id="search-component">
  <h4>Hero Search</h4>
  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
  <div>
    <div *ngIf = "heroes"> // this div is not working 
      no element found
    </div>
    <div *ngFor="let hero of heroes | async"
         (click)="gotoDetail(hero)" class="search-result" >
      {{hero.name}}
    </div>
  </div>
</div>

my hero-search.component.ts

import { Component, OnInit } from '@angular/core';
import { Router }            from '@angular/router';
import { Observable }        from 'rxjs/Observable';
import { Subject }           from 'rxjs/Subject';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
  selector: 'hero-search',
  templateUrl: 'hero-search.component.html',
  styleUrls: [ 'hero-search.component.css' ],
})
export class HeroSearchComponent implements OnInit {
  heroes: Observable<Hero[]>;
  private searchTerms = new Subject<string>();
  constructor(
    private heroSearchService: HeroSearchService,
    private router: Router) {}
  // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
    console.log("Heroes"+this.heroes);
  }
  ngOnInit(): void {

    this.heroes = this.searchTerms
      .debounceTime(300)        // wait for 300ms pause in events
      .distinctUntilChanged()   // ignore if next search term is same as previous
      .switchMap(term => term   // switch to new observable each time
        // return the http search observable
        ? this.heroSearchService.search(term)
        // or the observable of empty heroes if no search term
        : Observable.of<Hero[]>([]))
      .catch(error => {
        // TODO: real error handling
        console.log(error);
        return Observable.of<Hero[]>([]);
      });
  }
  gotoDetail(hero: Hero): void {
    let link = ['/detail', hero.id];
    this.router.navigate(link);
  }
}

* ngIf不能像添加按钮一样将英雄添加回阵列。

无论英雄阵列是否填充,div总是在页面中。

请帮忙。我是角度2的新手。

1 个答案:

答案 0 :(得分:0)

heroesOvservable<Hero[]>,我认为只有在数组为空时才会显示有问题的div。所以你的病情应该是*ngIf="(heroes | async)?.length == 0"。在当前的实现中,div始终显示,因为*ngIf评估为true,因为heroes有一个值,即 undefined