【问题标题】:Display element not found and add it to the list in angular2未找到显示元素并将其添加到 angular2 的列表中
【发布时间】:2017-01-15 07:54:56
【问题描述】:

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

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

我的 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 始终存在。

请帮忙。我是 Angular 2 的新手。

【问题讨论】:

    标签: angular angular-ng-if


    【解决方案1】:

    heroesOvservable&lt;Hero[]&gt; 并且我看到您只想在数组为空时显示有问题的div。所以你的条件应该是*ngIf="(heroes | async)?.length == 0"。在当前的实现中,div 总是出现,因为*ngIf 评估为true,因为heroes 有一个值,即它不是 undefined

    【讨论】:

    • 它的工作原理谢谢,但我能问一下为什么我们使用异步并且在输入一个不存在的英雄然后从输入框中删除它之后数据仍然存在意味着 *ngIf 仍然显示为未找到元素持续存在
    • 我们使用async 是因为heroes 不仅仅是一个数组,而是数组的Observable。 async 是一个实际上用作subscribe 的管道。它从 observable 中检索值。对于你的第二个问题:如果英雄不存在,那么数组将保持为空,因此会显示消息。
    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    相关资源
    最近更新 更多