【问题标题】:Custom CSS with Checkbox and NgFor带有复选框和 NgFor 的自定义 CSS
【发布时间】:2019-12-13 14:49:07
【问题描述】:

在使用*ngFor 进行迭代时,我正在尝试获取自定义复选框“可点击”。我有自定义 CSS,但点击事件没有任何效果。

我猜测是因为标签上的for 属性,但我不知道如何修复它。

Stackblitz:https://stackblitz.com/edit/angular-4znmwv?embed=1&file=src/app/app.component.css&view=editor

HTML:

<div *ngFor="let item of data">
  <input type="checkbox" [checked]= "item.selected" (change)="setChange(item, $event)">
  <label htmlFor="{{item.name}}">{{item.name}}</label>
</div>

CSS:

input[type="checkbox"] {
  position: absolute;
  height: 1px;
  width: 1px;
  overflow: hidden;
  clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
  clip: rect(1px, 1px, 1px, 1px);
}


input[type="checkbox"] + label {
  display: block;
  position: relative;
  padding: 0 1.5rem;
}


input[type="checkbox"] + label::before {
  content: '';
  position: relative;
  display: inline-block;
  margin-right: 10px;
  width: 20px;
  height: 20px;
  color: #2a3037;
  background-color: #fff;
  border-color: #1c8d3e;
}

input[type="checkbox"]:checked + label::before {
  color: #fff;
  background-color: #138630;
  border-color: #000000;
}

input[type="checkbox"]:checked + label::after {
  content: '';
  position: absolute;
  top: 3px;
  left: 27px;
  border-left: 2px solid black;
  border-bottom: 2px solid black;
  height: 6px;
  width: 13px;
  transform: rotate(-45deg);
}

input[type="checkbox"]:focus + label::before {
  outline: #5d9dd5 solid 1px;
  box-shadow: 0 0px 8px #5e9ed6;
}

input[type="checkbox"]:disabled + label {
  color: #575757;
}

input[type="checkbox"]:disabled + label::before {
  background: #ddb862;
}

【问题讨论】:

  • labels 使用属性for 而不是htmlFor

标签: javascript html css angular


【解决方案1】:

尝试这样,我刚刚为已由项目名称设置的复选框 id 的标签库设置了 for 属性

<div *ngFor="let item of data">
  <input type="checkbox"  [id]="item.name">
  <label [for]="item.name">{{item.name}}</label>
</div>

demo ?

【讨论】:

    【解决方案2】:
    <div *ngFor="let item of data;let i = index">
      <input type="checkbox" [checked]= "item.selected" id="{{item.name}}" (change)="setChange(item, $event)">
      <label for="{{item.name}}">{{item.name}}</label>
    </div>
    
    

    试试这个。

    将id设置为与标签的for相同,它将正常工作,for只是标签的属性名称,而不是htmlFor。

    如果您希望 id 与动态给出索引的 itemname 不同,我在这里添加了索引以供参考,像这样使用

    <div *ngFor="let item of data;let i = index">
      <input type="checkbox" [checked]= "item.selected" id="{{'checkbox'+i}}" (change)="setChange(item, $event)">
      <label for="{{'checkbox' + i}}">{{item.name}}</label>
    </div>
    

    这样你的 id 会是这样的

    复选框1

    复选框2

    ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-17
      • 2018-02-19
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2016-04-21
      • 1970-01-01
      相关资源
      最近更新 更多