Reputation: 345
In my working on angular 8 application where I am using primeng checkbox and I have some issue.Checkbox data is coming from db. So if status==0, I have to make it unchecked and if status==1, it should be selected even if load the table(default). I tried many ways and its not working. Can any one please point me the issue or any suggestions will be of great help.
onStatusChange(id: number,status: number) {
this.id = id;
console.log('Id', id);
console.log('Checked');
this.status = status;
console.log('Status', status);
}
<p-checkbox [value]="text.id" [(ngModel)]="status" binary="true" (onChange)="onStatusChange(TextID,status)"></p-checkbox>
{"Text":
[
{"ID":"1","Name":"Text","textContent":"content1,"status":"1"},
{"ID":"2","Name":"Text","textContent":"content1,"status":"1"},
{"ID":"3","Name":"Text","textContent":"content1,"status":"0"}
]
}
text.IsActive[text.IsActive==1?'true':'false'
I am getting the required data in onStatusChange to make it active or inactive for updating it to DB. But problem lies in making checkbox checked based on the selection while loading the data. Please help me.. stuck here for the last few days..
Upvotes: 1
Views: 15626
Reputation: 234
Instead of using the status directly as a number, you can map it to true
or false
with !!
1 => !!1 => true
0 => !!0 => false
If 1
or 0
should be a string then:
"1" => !!Number("1") => true
"0" => !!Number("0") => false
this allows you to use the values in the checkbox normally
Upvotes: 1
Reputation: 2164
I this you can use (ngModelChange)
instead of (onChange)
. The code is given below =>
HTML
<div>
<p-checkbox
label="My CheckBox"
binary="true"
[(ngModel)]="showLinkedRisksOnly"
(ngModelChange) ="myModelChanged($event)"
>
</p-checkbox>
</div>
<div>
Value: {{showLinkedRisksOnly}}
</div>
TS:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
showLinkedRisksOnly = true;
myModelChanged($event){
console.log($event);
}
}
NOTE: You can check the code in STACKBLITZ.
Upvotes: 2