【问题标题】:angular2 display after each loopangular2 在每个循环后显示
【发布时间】:2017-01-03 17:25:07
【问题描述】:

这可能是有史以来最愚蠢的问题,但请记住,我对 angular2 非常陌生。

在 angular2 中,如何在每个循环之后进行值渲染。我不想使用 *ngFor。就这样一个循环

@Component({
    templateUrl: 'app/categories/categories.component.html'
})
ngOnInit(){  
    export class CategoriesComponent implements OnInit {
        for(var i=0; i<this.categories.length; i++) {
           count=i;
        }
    }
}

每次循环后更新 html。

Loop number {{ count }}

谢谢。

【问题讨论】:

  • 您能否提供一些输入数据和预期输出的示例?除此之外,ngOnInit() 方法必须在组件内部...
  • @OliverHader 抱歉可以编辑我之前的评论。我没有任何输入,只是调用一个 api。
  • 为什么不想使用*ngFor
  • @GünterZöchbauer 我将复制并粘贴我在答案中告诉 lenny 的内容。所以我有一个类别列表(父),每个父类别都有一个子类别列表。我连接到 API,检索列表并显示父类别的名称。到目前为止,使用 ngFor 我可以做到这一点。现在,当我显示父类别列表时,我想检索每个父类别有多少子类别的计数。为此,我需要使用父 category_id 重新连接到 API,以检索子猫的数量。如何做到这一点?

标签: angular


【解决方案1】:

我不明白这个的用例是什么,但是你去吧:

categories.component.ts

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

@Component({
    templateUrl: 'app/categories/categories.component.html'
})
export class CategoriesComponent implements OnInit {
    private count: number;

    constructor(private changeDetectorRef: ChangeDetectorRef) { }

    ngOnInit(){  
        for(var i=0; i<this.categories.length; i++) {
           this.count=i;
           this.changeDetectorRef.detectChanges();
        }
    }
}

categories.component.html

<div>Loop number {{ count }}</div>

你不应该这样做。为什么不使用*ngFor

【讨论】:

  • 好吧,可能是我在这里使用了错误的方法。就像我说的非常非常新。从字面上看,数周 odl。所以我有一个类别列表(父),每个父类别都有一个子类别列表。我连接到 API,检索列表并显示父类别的名称。到目前为止,使用 ngFor 我可以做到这一点。现在,当我显示父类别列表时,我想检索每个父类别有多少子类别的计数。为此,我需要使用父 category_id 重新连接到 API,以检索子猫的数量。如何做到这一点?
  • 知道怎么做吗?
  • 请编辑您的问题或创建一个新问题,并展示您迄今为止尝试过的内容、显示父类别的组件等。
  • 你读过tour of heroes tutorial吗?它类似于您尝试做的事情,从 web api 加载数据列表并显示它。当您不熟悉 Angular 2 时,可以开始使用。
猜你喜欢
  • 2017-01-04
  • 2013-02-07
  • 2017-04-30
  • 2014-04-15
  • 2014-08-27
  • 2014-01-07
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多