【问题标题】:Counting items using ngFor with pipes -angular 2使用带有管道的 ngFor 计数项目 -angular 2
【发布时间】:2017-09-09 00:25:13
【问题描述】:

我基本上是在尝试计算 ngFor 指令概述的列表数量。我已经遵循了很多解决方案来解决我的问题,但这并不成功。下面是我的代码,我得到了错误,没有定义父级。

管道

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {


    parent : string;
    transform(value) : any {
        let keys = [];



        if(value) {

            this.parent = value;

            return Object.keys(value)
 }
    }
}

html

<div *ngFor="let game of games">

  <div *ngFor="let key of game| keys">

  <li> {{game[key].type}} </li>

  {{ game[key].location}}

    Count: {{game.parent.length}}

</div>


</div>

输出

 mario - germany
 kart - london
 rings - france 

total number of items  = 3

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    您可以使用 ngFor 的 index 代替自定义管道

    <div *ngFor="let game of games">
    
      <div *ngFor="let key of game| i=index ">
    
      <li> {{game[i].type}} </li>
    
      {{ game[i].location}}
    
        Count: {{game.parent.length}}
    
    </div>
    

    【讨论】:

    • 我想要显示的项目总数。没有列出项目旁边的数字
    • 你能给出一个示例 json 和预期的输出。 total number of items displayed can be calculated using games.length*..自己
    • 请看现在编辑的问题,看看输出
    • @XamarinDevil 你的问题解决了吗?
    【解决方案2】:

    你的计数应该在 div 之外,

    <div *ngFor="let game of games">
      <div *ngFor="let key of game| i=index ">
      <li> {{game[i].type}} </li>
      {{ game[i].location}}   
    </div>
    <div>
     total number of items: {{game.parent.length}}
    </div>
    

    【讨论】:

    • 这会引发错误Unhandled Promise rejection: Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined
    • 另外,我确实需要使用按键来显示数据
    • 你在哪里使用 toUpperCase?
    • 我没有使用 toUpperCase 但该错误是由 i = index
    • 你为什么突然出现这个错误?它以前工作正常吗?
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2017-03-13
    • 2017-02-02
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2019-05-15
    • 2017-04-05
    相关资源
    最近更新 更多