首页 > 解决方案 > 如何仅在选定项目上动态应用 CSS [Angular]

问题描述

我在学习Angular。我month-picker从头开始创建了一个自定义。它选择一系列月份,没有日期和星期。我想强调选择的月份范围。您可以想到primeng月份选择器,但有范围。我尝试了这个这个和许多其他解决方案,但我失败了。这是我的代码:

monthpicker.component.html

<div class="my-table-div dropdown-content">
  ...
  <br>
  <div *ngFor="let row of matrix" class="my-table">
    <span *ngFor="let x of row">
      <span class="month-name" (click)="onClick(x)" [class.extraStyle]="someProperty">
        {{ x }}
      </span>
    </span>
  </div>
</div>

monthpicker.component.ts

  ...
  clickCount: number =0; /*to determine lower bound and upper bound selection*/
  someProperty:boolean=false;
  flag:boolean= false;

  ...
  arr = [
    'Jan', 'Feb', 'Mar', 'Apr',
    'May', 'Jun', 'JuL', 'Aug',
    'Sep', 'Oct', 'Nov', 'Dec'
  ];
  ...

  n = 4;
  matrix = Array
    .from({ length: Math.ceil(this.arr.length / this.n) }, (_, i) => i)
    .map(i => this.arr.slice(i * this.n, i * this.n + this.n));

  ...

  onClick(x) {
    this.clickCount++;
    console.log("Month: " + x);
    if(this.clickCount%2!=0) {
      this.lowerMonth= x;
      this.lowerYear=this.year;
    }
    console.log("Year: " + this.lowerYear);
    console.log("Clicked "+this.clickCount +" times.");
    if(this.clickCount%2==0) {
      this.upperMonth=" "+x;
      this.upperYear =this.year;
      if(this.flag) {
        this.someProperty=true;
      }
      else {
        this.someProperty=false;
      }
    } 
  }

这是我正在应用的css monthpicker.component.css

.extraStyle {
    background-color: #1474A4 !important;
    color: white !important;
    text-align: center !important;
}

结果如下: 在此处输入图像描述

看,CSS 适用于所有月份,即使选择仅从一月到七月。

有什么方法可以将 cssindex仅应用于选定的数字。因为索引从 0 到 11 开始,并且每个月都是固定的。好吧,这就是我的想法,对不起,我可能完全错了。请纠正我并帮助我实施。

标签: htmlcssangularprimeng

解决方案


您可以在行数组中添加 isSelected 键。像这样 :

matrix: any = Array.from(
    { length: Math.ceil(this.arr.length / this.n) },
    (_, i) => i
  ).map(i =>
    this.arr.slice(i * this.n, i * this.n + this.n).map(x => ({
      monthName: x,
      isSelected: false
    }))
  );

而不是像这样在 html 中使用 isSelected 键:

<div *ngFor="let row of matrix" class="my-table">
    <span *ngFor="let x of row">
      <span class="month-name" (click)="onClick(x); x.isSelected = !x.isSelected" [ngClass]="{'extraStyle' : x.isSelected }">
        {{ x.monthName }}
      </span>
    </span>
</div>

推荐阅读