Reputation: 113
I am trying to get a custom check box 'clickable' when being iterated on with an *ngFor
. I have the custom CSS, but nothing is working on the click event.
I am guessing that it is because of the for
property on the label, but I don't know how to fix it.
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;
}
Upvotes: 1
Views: 459
Reputation: 24404
try like this , I have just set the for attribute for the label base of the checkbox id that have been set by item name
<div *ngFor="let item of data">
<input type="checkbox" [id]="item.name">
<label [for]="item.name">{{item.name}}</label>
</div>
Upvotes: 1
Reputation: 1635
<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>
Try this.
Set the id as the same as the for of the label it will work properly and for
is only the attribute name for label and not htmlFor.
Here i have added index for reference if you want the id to be different from the itemname which is dynamically gives index Use like this
<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>
This way your id would be something like this
checkbox1
checkbox2
...
Upvotes: 0