Reputation: 7096
I created a custom checkbox component that looks like this:
checkbox.component.ts
import {Component, Input, OnInit, forwardRef} from "@angular/core"
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"
@Component({
selector: "checkbox",
template: `
<input type="checkbox" [checked]="checked" (change)="checkedChanged($event)" [id]="id">
<label [for]="id"><span>{{checked ? "✓" : " "}}</span></label>
`,
styles: [`
input {
opacity: 0;
position: fixed;
}
label {
line-height: 16px;
height: 16px;
width: 16px;
border-radius: 5px;
font-size: 16px;
color: #000000;
background-color: #ffffff;
margin-bottom: 0;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
`],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxComponent),
multi: true
}
]
})
export class CheckboxComponent implements OnInit, ControlValueAccessor {
static idCounter = 1
@Input() id: string
checked: boolean
propagateChange = (_: any) => {}
onTouchedCallback = () => {}
ngOnInit () {
// If an ID wasn't provided, generate a unique one
if (!this.id) {
this.id = "checkboxcomponent" + CheckboxComponent.idCounter++
}
}
checkedChanged (event) {
this.checked = event.target.checked
this.propagateChange(event.target.checked)
}
// ControlValueAccessor requirements
writeValue (value: any) {
this.checked = value
}
registerOnChange (func: any) {
this.propagateChange = func
}
registerOnTouched (func: any) {
this.onTouchedCallback = func
}
}
html example
<div class="col-4 text-right">
<label for="foo">Foo:</label>
</div>
<div class="col-8">
<checkbox [(ngModel)]="bar" id="foo"></checkbox>
</div>
The checkbox itself works perfectly, but the label doesn't. I wanted to pass in the ID as an input so I could connect it to an external label (the label positioning is different in different parts of the app, so I couldn't include it in the component), and inspecting the page shows that it's using the correct ID, but clicking the label doesn't toggle the checkbox. I assume it's some sort of scoping issue with the component, but I'm not sure how to handle that. Is there a way to make it work without having to add an extra (click)
function or something every time I use it?
Upvotes: 1
Views: 641
Reputation: 3004
If you change
@Input id: string;
to
@Input checkboxId: string;
and use it in <checkbox [(ngModel)]="bar" checkboxId="foo"></checkbox>
it will work just fine.
https://stackblitz.com/edit/angular-qxjb4q
Upvotes: 4