繁体   English   中英

带有复选框和 NgFor 的自定义 CSS

[英]Custom CSS with Checkbox and NgFor

当使用*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;
}

像这样尝试,我刚刚为已按项目名称设置的复选框 ID 的标签基础设置了 for 属性

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

演示

<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

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM