<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?
not use "banana syntax"
<input type="checkbox"
[ngModel]="rowData.active=='true'?true:false"
(ngModelChange)="rowData.active=$event?'true':'false'"
>
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'};
In html
<input type='checkbox' [(ngModel)]='rowData.active'>
in ts
rowData={'active' : true}
Working StackBligz
If you use primeng, ref PrimeNg
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)
.
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';
}
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 -
p-checkbox
or normal input type text. –
Wallinga © 2022 - 2024 — McMap. All rights reserved.