<input pInputText type="checkbox" [(ngModel)]="rowData.active">
active is a string. It's value is 'true' or 'false'. I wanna bind this string value to a checkbox.
So how can I do that?
-
Can't you parse it before you bind the value? And if backend requires it, parse it again before sending to the API.Chrillewoodz– Chrillewoodz2019-09-26 09:04:41 +00:00Commented Sep 26, 2019 at 9:04
6 Answers
not use "banana syntax"
<input type="checkbox"
[ngModel]="rowData.active=='true'?true:false"
(ngModelChange)="rowData.active=$event?'true':'false'"
>
In html
<input type='checkbox' [(ngModel)]='rowData.active'>
in ts
rowData={'active' : true}
Working StackBligz
If you use primeng, ref PrimeNg
Comments
If you use <input type="checkbox">, then it is possible to use the following syntax to bind:
<input
type="checkbox"
[checked]="(rowData.active === 'true') ? true : false"
(change)="rowData.active = $event.target.checked"
/>
<p> rowData.active {{ rowData.active }}</p>
TypeScript:
rowData = {active: 'true'};
Comments
An alternative solution would be to use get and set in your component code. First use a dedicated variable in your HTML. <input pInputText type="checkbox" [(ngModel)]="rowIsActive">. Then in your component add the following:
...
get rowIsActive(): boolean {
return this.rowData.active !== '';
}
set rowIsActive($event: boolean) {
return this.rowData.active = $event ? "true" : ""';
}
...
That way, you can still use the 'Banana in a box' syntax and reliably convert boolean to string values without the additional (ngModelChange).
Comments
I had issues with some of the other solutions where I had to click a checked checkbox twice to uncheck it (I'm using Angular 18)
The following code works for me where my string value should be either "true" or "false"
Note - the order of (change) and [checked] makes a difference
<input type="checkbox" (change)="checkboxChange($event)" [checked]="value === 'true'">
Typescript
checkboxChange(event: any) {
this.value = event.target.checked ? 'true' : 'false';
}
Comments
You will need to add binary="true" attribute in your HTMLElement.
As per my understanding you are using primeng's checkbox. So code should be like this -
<p-checkbox [(ngModel)]="rowData.active" binary="true"></p-checkbox>
For more in details read out the whole documentation here -
2 Comments
p-checkbox or normal input type text.