用切片拆分二维数组打字稿html

时间:2021-01-29 16:19:21

标签: html typescript matrix multidimensional-array slice

我正在尝试使用 slice 在我的页面视图中拆分矩阵的列。如果我 slice:0:1,页面只显示第一列。但我不明白为什么如果我尝试选择 slice:1:2 它不会只显示第二列,而仍然只显示第一列。 2:33:4 等相同。

<div class="container">    
    <tr *ngFor="let row of matrix; index as r">
        <td *ngFor="let column of row|slice:0:1; index as c">
            
            <select [(ngModel)]="object[r][c]">
            {{r}}{{c}}
            </select>
        
        </td>
    </tr>
</div>
ngOnInit() {
    for (let r = 0; r < 6; r++) {
      this.normalizedMatrix.push([0, 0, 0, 0, 0, 0])
      this.matrix[r] = []
      this.object[r] = {}
      this.object[r][r] = 1
      for (let c = 0; c < 6; c++) {
        if (r == c) {
          this.matrix[r].push(1)
          this.object[r][c] = 1
        }
        if (r > c) {
          this.matrix[r].push(1 / 9)
          this.object[r][c] = 1 / 9
        }
        else if (r < c) {
          this.matrix[r].push(9)
          this.object[r][c] = 9
        }
      }
    }
    this.onSelectChange(0, 0)
  }

1 个答案:

答案 0 :(得分:1)

Here is a working example of the pipe. 似乎您只是在查看列索引值,该值会随管道值而变化。这是因为切片管道的作用类似于 js 切片,因为它“创建一个包含元素子集(切片)的新数组或字符串”。 ng docs

//component.html
<div class="container">
    <tr *ngFor="let row of matrix; index as r">
        <td *ngFor="let column of row|slice:1:2; index as c">

            <p>R: {{r}} C: {{c}} - {{column}}</p>>

        </td>
    </tr>
</div>


//component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  matrix = [
    ['row 1 col 1', 'row 1 col 2'],
    ['row 2 col 1', 'row 2 col 2'],
    ['row 3 col 1', 'row 3 col 2']
  ];
}