检查角度5 * ngIf中的数组长度

时间:2018-02-22 02:42:50

标签: angular

我正在做* ngif以检查fitered结果长度是否为0显示项目否则显示模板错误。

不幸的是,只有当过滤后的结果有项目时,templateref才有效。

如果没有,则result.length不显示任何内容。

<div *ngFor="let collection of collections | async | filterBy: ['title']: search as result">
       <ng-container *ngIf='result?.length != 0; 
           then resultsIs else noresults'>
       </ng-container>

        <ng-template #resultsIs>
          <a routerLink="/collections/c/{{collection.title | 
            slugify}}/{{collection.id}}" 
               class="list-group-item list-group-item-action flex-column align-items-start"
          >
        <div class="d-flex w-100 justify-content-between">
          <h5 class="mb-1 text-primary"><u>{{collection.title}}</u></h5>
           <small>{{collection.updatedAt}}</small>
           </div>
           <p class="text-muted" >{{collection.description}}</p>
           <small>{{collection.username}}</small>
      </a>
    </ng-template>

    <ng-template #noresults>
     <div class="alert alert-info">
    <strong>No Match Found!</strong>
     Widen your search.</div>
       </ng-template>
     </div>

如果此对象数组长度小于零,如何正确检查,以便显示模板的这一部分

 <ng-template #noresults>
        <div class="alert alert-info"><strong>
          No Match Found!</strong> Widen your search.
         </div>
</ng-template>

1 个答案:

答案 0 :(得分:1)

模板的* ngIf位于ngFor内,它遍历已过滤的列表。

我不确定你是如何实现过滤管的,但我想如果集合列表与过滤条件不匹配,它将返回一个空集。

在这种情况下,作为正常行为,ngFor将不会渲染任何元素,因此内部的所有内容都不会被角度

评估

如果为ngFor提供的列表中没有元素,则需要指定默认模板。目前尚不支持此功能,但通过查看此请求的最新提交,可能很快就会提供

https://github.com/angular/angular/issues/14479

Meanwile,你可以做这样的事情

<div *ngIf='collections | async | filterBy: ['title']: search'; let filteredCollections>


    <div *ngFor="let collection of filteredCollections">


              <a routerLink="/collections/c/{{collection.title | 
                slugify}}/{{collection.id}}" 
                   class="list-group-item list-group-item-action flex-column align-items-start"
              >
            <div class="d-flex w-100 justify-content-between">
              <h5 class="mb-1 text-primary"><u>{{collection.title}}</u></h5>
               <small>{{collection.updatedAt}}</small>
               </div>
               <p class="text-muted" >{{collection.description}}</p>
               <small>{{collection.username}}</small>
          </a>


     </div>



    <div class="alert alert-info" *ngIf='filteredCollections.length === 0'>
        <strong>No Match Found!</strong>
        Widen your search.
    </div>

</div>
相关问题