【问题标题】:Increment counter for nested for loop in AngularAngular中嵌套for循环的增量计数器
【发布时间】:2021-10-23 14:34:14
【问题描述】:
<tr *ngFor="let adjustment of adjustments; let i = index">
  <td *ngFor="let blade of adjustment.blades; let j = index">
    <span> Counter = {{ ???? }} </span>
  </td>
</tr>
adjustments= [[blades: [a]], 
              [blades: [a]], 
              [blades: [a,b,c]], 
              [blades: [a,b]]
             ]

输出:

计数器 = 1

计数器 = 2

计数器 = 3

计数器 = 4

计数器 = 5

计数器 = 6

【问题讨论】:

  • 欢迎来到 Stack Overflow。请把你的问题说清楚。见How to Ask

标签: javascript angular angular6


【解决方案1】:

你为什么不在代码中展平数组并在展平的数组之上遍历。

这样会更简单:

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());

方法2

您可以编写 2 个函数来获取计数和对象:

  getBlade(i,j) {
    return this.adjustments[i].blades[j];
  }

 getCount(i: number, j: number) {
    let len= 0;
    for(let x = 0; x<i; x++) {
      len = len + this.adjustments[x].blades.length;
    } 
    return len + (j+ 1);
  }

然后在 HTML 中,您可以查找对象或计数:

<tr *ngFor="let adjustment of adjustments; let i = index">
  <td *ngFor="let blade of adjustment.blades; let j = index">
    <span> Counter = {{ getCount(i,j) }} : {{getBlade(i,j)}} , 
    </span>
  </td>
</tr>

【讨论】:

  • 这是用于导航和子导航的,我们必须遍历页面索引。所以 flatten 在这里不起作用,因为如果数组是 const arr1 = [0, 1, 1, [1, 2]];
  • 谢谢,根据您的解释,我已经用另一种方法更新了答案。请检查。
【解决方案2】:

您可以使用附加到您要计算的元素的指令来实现它:

@Directive({
  selector: '[appCounter]',
  exportAs: 'appCounter'
})
export class CounterDirective implements AfterViewInit {
  static nextIndex = 0;

  @Input() appCounter: number | string = '';

  index;

  constructor() {
    this.index = CounterDirective.nextIndex++;
  }
  
  ngAfterViewInit(): void {
    if (typeof this.appCounter === 'string') {
      return;
    }
    CounterDirective.nextIndex = this.appCounter;
  }
}

在模板中的用法:

<ng-container [appCounter]="0">
  <tr *ngFor="let adjustment of adjustments; let i = index">
    <td *ngFor="let blade of adjustment.blades; let j = index">
      <span #counter="appCounter" appCounter> Counter = {{ counter.index }} </span>
    </td>
  </tr>
</ng-container>

ng-container 用于重置计数器。

StackBlitz example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多