角度为4的动态类

时间:2018-01-30 01:28:38

标签: angular

我尝试使用ngFor创建列表,我需要<li>标记有一个动态类,从hex-0到hex-19,但我得到它:< / p>

&#13;
&#13;
<ul class="hex-container">
        <li *ngFor="let total of item1;let i=index" [ngClass]="'hex hex-'+ i"></li>
        <li *ngFor="let total of item2;let i=index" [ngClass]="'hex hex-'+ i"></li>
        <li *ngFor="let total of item3;let i=index" [ngClass]="'hex hex-'+ i"></li>
        <li *ngFor="let total of item4;let i=index" [ngClass]="'hex hex-'+ i"></li>
      </ul>
      
      
      
// I got

<ul _ngcontent-c9="" class="hex-container">
    <!---->
    <li _ngcontent-c9="" class="hex hex-0"></li>
    <li _ngcontent-c9="" class="hex hex-1"></li>
    <li _ngcontent-c9="" class="hex hex-2"></li>
    <li _ngcontent-c9="" class="hex hex-3"></li>
    <li _ngcontent-c9="" class="hex hex-4"></li>
    <li _ngcontent-c9="" class="hex hex-5"></li>
    <li _ngcontent-c9="" class="hex hex-6"></li>
    <!---->
    <li _ngcontent-c9="" class="hex hex-0"></li>
    <li _ngcontent-c9="" class="hex hex-1"></li>
    <li _ngcontent-c9="" class="hex hex-2"></li>
    <li _ngcontent-c9="" class="hex hex-3"></li>
    <li _ngcontent-c9="" class="hex hex-4"></li>
    <li _ngcontent-c9="" class="hex hex-5"></li>
    <li _ngcontent-c9="" class="hex hex-6"></li>
    <li _ngcontent-c9="" class="hex hex-7"></li>
    <li _ngcontent-c9="" class="hex hex-8"></li>
    <li _ngcontent-c9="" class="hex hex-9"></li>
    <li _ngcontent-c9="" class="hex hex-10"></li>
    <!---->
    <li _ngcontent-c9="" class="hex hex-0"></li>
    <li _ngcontent-c9="" class="hex hex-1"></li>
    <!---->
</ul>
&#13;
&#13;
&#13;

我需要做什么才能将类hex-0转换为hex-19或更多?

UPDATE:我需要为项目N1,N2,N3和N4设置一个特定的类,例如class =&#34; hex hex-0 n1&#34;,class =&#34 ; hex hex-1 n2&#34;,...

1 个答案:

答案 0 :(得分:4)

尝试将数组与扩展运算符

组合在一起

在component.ts

  totalSquadsN1 = [1, 2, 3, 4];
  totalSquadsN2 = [1, 2, 3, 4];
  totalSquadsN3 = [1, 2, 3, 4];
  totalSquadsN4 = [1, 2, 3, 4];
  totalSquads = [...this.totalSquadsN1, ...this.totalSquadsN2, ...this.totalSquadsN3, ...this.totalSquadsN4];
component.html中的

<ul _ngcontent-c9="" class="hex-container">
<li *ngFor="let total of totalSquads;let i=index" [ngClass]="'hex hex-'+ i">{{i}}</li>
</ul >

更新,因为问题已经发展......

如果你需要将一组数组合并到一个长列表中,但是为每个数组分配一个特定的类,你可以使用forEach方法(注意:这只是一个例子)

  totalSquadsN1 = [1, 2, 3, 4];
  totalSquadsN2 = [1, 2, 3, 4];
  totalSquadsN3 = [1, 2, 3, 4];
  totalSquadsN4 = [1, 2, 3, 4];
  totalSquads = [];

  constructor() {
    let i = 1;
    let arrays = [this.totalSquadsN1, this.totalSquadsN2, this.totalSquadsN3, this.totalSquadsN4];
    arrays.forEach((array) => {
      array.forEach((instance) => {
        this.totalSquads.push({value: instance, class: 'n' + i});
      });
      i++;
    });
  }

然后在你的HTML中

<ul _ngcontent-c9="" class="hex-container">
  <li *ngFor="let total of totalSquads;let i=index" [ngClass]="'hex hex-'+ i +  ' ' +  total.class ">{{i}}</li>
</ul >