【问题标题】:Using *ngIf along with angular4 custom pipes使用 *ngIf 和 angular4 自定义管道
【发布时间】:2018-06-18 03:03:31
【问题描述】:

我正在使用一个自定义管道,它根据数组字符串中的第一个字母(电话目录样式)过滤数组。每当我更改字母参数时,管道都会返回过滤后的数组并使用 *ngFor 显示它。如果未找到匹配项,则返回空数组,并且我的显示为空白。

我希望如果管道返回空数组,我的显示区域应该显示一个 div '未找到记录'。我该怎么做。

<div *ngIf="currentList.length > 0; else nodata" id="outerContainer">
    <div id="listContainer">
        <div class="listItem" *ngFor="let list of currentList | listFilter : listfilterChar" (click)="openContactList()">
            <div class="listInfo">
              <h3>
                {{list.Name}}
              </h3>
          </div>
    </div>
    <div id="alphabetContainer">
      <p *ngFor="let letter of alphabetArray">
        <span class="alphabetContainer" (click)='setListFiltercharacter($event)'>{{letter}}</span>
      </p>
    </div>
  </div>

在上面点击span.alphabetContainer的代码中,变量listfilterChar被更新为字母表,管道过滤数组。但是如果没有找到匹配的初始字母显示区域的联系人保持空白。

【问题讨论】:

  • 但我认为使用另一个具有否定值的 div 比这个 ngIf-else 更具可读性。
  • 嘿,你的 else nodata div 在哪里?在那个 div 你应该提到你的错误。它将像数组不为空或大于零一样执行它将显示 {{list.Name}} else nodata div。
  • 我认为管道不是直接操作 currentList 数组。它返回一个新数组,因此 currentList.length == 0,不起作用
  • 不相关,但在 Angular2+ 中不鼓励过滤/排序管道

标签: angular


【解决方案1】:

试试这个

<div class="listItem" *ngFor="let list of currentList | listFilter : listfilterChar" (click)="openContactList()">
    <div class="listInfo">
        <h3>
            {{list.Name}}
        </h3>
    </div>
</div>
<div *ngIf="(currentList | listFilter : listfilterChar).length === 0">
    "No record found"
</div>

【讨论】:

    【解决方案2】:

    按照这个article,更好的方法是这样做:

    <ng-container *ngIf=”(currentList | listFilter : listfilterChar) as result”>
    
      <div *ngFor=”let item of result”>
        {{item}}
      </div>
    
      <b *ngIf="!result.length">No record found</b>
    
    </ng-container>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 2013-01-20
      相关资源
      最近更新 更多