将nth-child绑定到数组,Angular

时间:2019-02-27 00:04:23

标签: angular

我的Angular应用程序中有一个数字数组和一个<ul>,如下所示:

@Component({
  selector: 'my-app',
  template: `
     <ul>
        <li>Line: 1</li>
        <li>Line: 2</li>
        <li>Line: 3</li>
        <li>Line: 4</li>
        <li>Line: 5</li>
        <li>Line: 6</li>
        <li>Line: 7</li>
        <li>Line: 8</li>
        <li>Line: 9</li>
        <li>Line: 10</li>
        <li>Line: 11</li>
        <li>Line: 12</li>
    </ul>
  `,
})
export class AppComponent  {
  list: number[] = [2, 5, 7];
}

我想选择列表数组中的所有nth-child,因此生成的CSS应该如下所示:

li:nth-child(2),
li:nth-child(5),
li:nth-child(7) {
  background-color: red;
}

有人知道我如何通过角度绑定来操纵CSS选择器(第n个)?

1 个答案:

答案 0 :(得分:1)

如果这个列表像您所说的那样动态,那么我认为最好的方法是working example

@Component({
  selector: 'my-app',
  template: `
     <ul>
        <li *ngFor='let n of list' <!-- for each number in list -->
          [ngClass]='{"chosen": selectedList.includes(n)}'> <!-- apply class if n is in selectedList -->
          List: {{n}}</li>
    </ul>
  `,
  styles: [`.chosen{color: #f00;}`]
})
export class AppComponent  {
  list: number[] = [1,2,3,4,5,6,7,8,9,10,11,12];
  selectedList: number[] = [2, 5, 7];
}

请注意listselectedList的新定义