【问题标题】:How to toggle click a single elements CSS class in Angular 2?如何在 Angular 2 中切换单击单个元素 CSS 类?
【发布时间】:2021-01-18 15:17:10
【问题描述】:

我正在循环一个 API 响应并在页面上显示一些项目(女性和男性年龄组),代码如下:

<ng-container *ngFor="let event of day.availableEvents">
    {{ event.name }}
    <br>
    <ng-container *ngFor="let maleAgeGroup of event.maleAgeGroups">
      <span [class.is-active]="status" (click)="updateStatus()" {{ maleAgeGroup }}</span>
    </ng-container>
</ng-container>

而且,这是我正在使用的 JSON 数据:

"days": [
  {
    "date": "2021-04-14T00:00:00.000Z",
    "availableEvents": [
      {
        "id": 1,
        "name": "Event A",
        "femaleAgeGroups": ["U13", "U15", "U17"],
        "maleAgeGroups": ["U13", "U15", "U17"]
      },
      {
        "id": 2,
        "name": "Event B",
        "femaleAgeGroups": ["U13", "U15", "U17"],
        "maleAgeGroups": ["U13", "U15", "U17"]
      },
    ]
  }
]

点击某个年龄组时,我想将其状态从真或假切换,以便添加/删除 is-active CSS 类。

无论我尝试什么 SO 答案,我都无法让它工作,并且在大多数情况下最终会出现“无法将状态分配给类型字符串”之类的错误。这就是为什么我将上面的代码从根本上剥离——也许是因为我的数据的结构方式?

下面的示例是我试图结束的示例,其中突出显示的文本已被单击并应用了 is-active 类:

【问题讨论】:

  • updateStatus() 是做什么的?

标签: javascript angular typescript


【解决方案1】:

[class.is-active] 需要“绑定”到一个值,我不清楚您作为一个整体尝试做的事情的意图,但是,每个年龄组都需要一个状态。因此,您需要从服务器更新/修改您的数据,或者在您的组件中增加每个年龄段的状态...

"femaleAgeGroups": [{name:"U13", active:true}, {name:"U15", active:false}, {name:"U17", active:false}], etc..

然后在模板中可以将css类绑定到布尔值

 <ng-container *ngFor="let maleAgeGroup of event.maleAgeGroups">
      <span [class.is-active]="maleAgeGroup.active" (click)="updateStatus(maleAgeGroup)" {{ maleAgeGroup.name }}</span>
    </ng-container>

.. 并更新您将项目传递给更新功能并更新其活动状态:

updateStatus(item:any): void {
   item.active = !item.active;
}
 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多