【问题标题】:Angular if-then-else conditionalsAngular if-then-else 条件句
【发布时间】:2023-03-08 14:40:01
【问题描述】:

问题

我正在尝试在搜索服务忙于检索和过滤结果时显示微调器。我认为*ngIf 的较新 Angular 语法可以让您在 if 条件之外还有一个 else 条件。但是每当我开始输入时,微调器就会正确显示,然后控制台中的错误会在更改检测运行后抱怨值发生更改。

  • 如何解决此问题?
  • 对组件成员/属性的更改是否会反映在视图中?为什么更改检测不解决这个问题,而不是抱怨我的时间安排?

组件

@Component({
  selector: 'app-help-search',
  templateUrl: './help-search.component.html',
  styleUrls: ['./help-search.component.scss'],
  providers: [HelpSearchService]
})
export class HelpSearchComponent implements OnInit {
  searching: boolean;
  helpItems: Observable<HelpItem[]>;
  private searchTerms = new Subject<string>();

  constructor(
    private alertService: AppLevelAlertService,
    private helpSearchService: HelpSearchService,
    private router: Router) { }

  /**
   * Push a search term into the observable stream.
   */
  search(term: string): void {
    this.searching = true;
    this.searchTerms.next(term);
  }

  ngOnInit() {
    this.helpItems = this.searchTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(term => term
        ? this.helpSearchService.search(term)
        : Observable.of<HelpItem[]>([])
      )
      .catch(error => {
        this.alertService.errorOccurred.emit(new Error(error._body.error));
        return Observable.of<HelpItem[]>([]);
      })
      .finally(() => this.searching = false);
  }

  gotoHelpItem(helpItem: HelpItem): void {
    this.router.navigateByUrl(helpItem.url.toString());
  }

}

组件模板

<div id="search-component">
  <div class="form-group">
    <label for="search-box">Search for help topics: </label>
    <input type="text" #searchBox id="search-box" (keyup)="search(searchBox.value)" style="display: block; width: 100%; font-size: 20pt; height: 25pt" />
  </div>
  <div *ngIf="searching; then spinner else searchResults"></div>
  <ng-template #spinner>
    <span class="spinner spinner-lg">
      Loading...
    </span>
  </ng-template>
  <ng-template #searchResults>
    <div *ngFor="let helpItem of helpItems | async" (click)="gotoHelpItem(helpItem)" class="search-result">
      <app-help-item [helpItem]="helpItem"></app-help-item>
    </div>
  </ng-template>
</div>

我尝试过的

我注意到在.finally 谓词中将this.searching 设置为false 是导致此问题的原因。而不是这种方法,我尝试订阅this.helpItems 并在next 谓词设置this.searchingfalse。当结果返回时,这会正确移除微调器。但不幸的是,这仍然不起作用,因为 for 循环没有取代微调器的位置。结果返回后,ng-templates 都会消失。

【问题讨论】:

  • 您没有订阅数据。你想达到什么目的?
  • 我正在尝试让帮助项目显示在视图中。如果我不包括微调器,它在视图中显示得很好。但我试图让微调器出现,直到呈现搜索结果。有意义吗?

标签: angular binding angular2-changedetection


【解决方案1】:

我采取了不同的方法来解决这个问题。我没有使用新的*ngIf if-then-else 条件来决定渲染哪个ng-template,而是选择覆盖微调器并使用css 来控制它的可见性。这是对我来说效果很好的改变方法:

组件

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subject } from 'rxjs/Rx';

import { AppLevelAlertService } from '../alerts/app-level-alert.service';
import { HelpItem } from '../help-item';
import { HelpSearchService } from '../help-search.service';

@Component({
  selector: 'app-help-search',
  templateUrl: './help-search.component.html',
  styleUrls: ['./help-search.component.scss'],
  providers: [HelpSearchService]
})
export class HelpSearchComponent implements OnInit {
  @ViewChild('overlay') overlay: ElementRef;

  searching: Subject<boolean> = new Subject<boolean>();
  helpItems: Observable<HelpItem[]>;

  private searchTerms = new Subject<string>();

  constructor(
    private alertService: AppLevelAlertService,
    private helpSearchService: HelpSearchService) {
    this.searching.subscribe(searching => this.overlay.nativeElement.style.display = searching ? 'block' : 'none');
  }

  /**
   * Push a search term into the observable stream.
   */
  search(term: string): void {
    this.searching.next(true);
    this.searchTerms.next(term);
  }

  ngOnInit() {
    this.helpItems = this.searchTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(term => {
        const results = term
          ? this.helpSearchService.search(term)
          : Observable.of<HelpItem[]>([]);
        return results;
      })
      .catch(error => {
        this.alertService.errorOccurred.emit(new Error(error._body.error));
        return Observable.of<HelpItem[]>([]);
      });
    this.helpItems.subscribe(thing => this.searching.next(false));
  }

}

模板

<div id="search-component">
  <div class="form-group">
    <label for="search-box">Search: </label>
    <input type="text" #searchBox id="search-box" (keyup)="search(searchBox.value)" />
  </div>
  <div #overlay id="overlay">
    <span class="spinner spinner-lg">
      Loading...
    </span>
  </div>
  <app-help-item *ngFor="let helpItem of helpItems | async" [helpItem]="helpItem"></app-help-item>
</div>

造型

#search-box {
  display: inline-block;
  font-size: 20pt;
  height: 25pt
}

#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.3);
  z-index: 2;
  .spinner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -ms-transofrm: translate(-50%, -50%);
  }
}

【讨论】:

    猜你喜欢
    • 2018-08-02
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多