Angular - 操作模板中的变量

问题描述 投票:0回答:1
angular ngfor angular-structural-directive
1个回答
0
投票

我们可以调整 for 循环,以便

i+j
为您提供
1 to 8
中的所有数字,请参阅以下工作示例供您参考!

完整代码:

import { Component } from '@angular/core';
import { RouterModule, provideRouter } from '@angular/router';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterModule],
  template: `
    @for (i of [0, 3, 6]; track i) {
      <div class="row">
        @for (j of [0, 1, 2]; track j) {
          <div class="col-12 col-sm-6 col-md-4">
            <a
              [routerLink]="[
                mostViewedArticles[i + j].category +
                '/' +
                mostViewedArticles[i + j].id +
                '/' +
                mostViewedArticles[i + j].title
              ]"
            >
              <h5>{{i + j + 1}}. {{ mostViewedArticles[i + j].title }}</h5>
            </a>
          </div>
        }
      </div>
    }
  `,
})
export class App {
  name = 'Angular';
  mostViewedArticles = [
    {
      category: 'test1',
      id: 1,
      title: 'test1',
    },
    {
      category: 'test2',
      id: 2,
      title: 'test2',
    },
    {
      category: 'test3',
      id: 3,
      title: 'test3',
    },
    {
      category: 'test4',
      id: 4,
      title: 'test4',
    },
    {
      category: 'test5',
      id: 5,
      title: 'test5',
    },
    {
      category: 'test6',
      id: 6,
      title: 'test6',
    },
    {
      category: 'test7',
      id: 7,
      title: 'test7',
    },
    {
      category: 'test8',
      id: 8,
      title: 'test8',
    },
  ];
}

bootstrapApplication(App, {
  providers: [
    provideRouter([]),
  ]
});

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.