Reputation: 2277
I have a JSON where some fields are boolean, but unfortunatelly they values aren't 1/0 or true/false. Instead of that they have values "Y"/"N" and i struggle with it.
I'm trying to set checked attribute basing on condition like:
[checked]="myobj.isdeleted == 'Y' ? true : false"
[attr.checked]="myobj.isdeleted == 'Y' ? true : false"
or
[checked]="myobj.isdeleted == 'Y' ? true : null"
[attr.checked]="myobj.isdeleted == 'Y' ? true : null"
but none of them works. Any ideas how to achieve that?
Full markup:
<input type="checkbox" name="isdeleted" [checked]="myobj.isdeleted=='T' ? true : false" id="isdeleted" [(ngModel)]="myobj.isdeleted">
Upvotes: 1
Views: 72
Reputation: 73761
You can write a property in the component class:
public get isObjectDeleted(): boolean {
return this.myobj.isdeleted === "Y";
}
public set isObjectDeleted(value: boolean) {
this.myobj.isdeleted = value ? "Y" : "N";
}
and use that property for ngModel
, as shown in this stackblitz:
<input type="checkbox" [(ngModel)]="isObjectDeleted" name="isdeleted" id="isdeleted" />
If you want to pass the name of the property (e.g. isdeleted
) as an argument, you can use [ngModel]
and (ngModelChange)
separately:
<input type="checkbox" [ngModel]="isChecked('prop1')" (ngModelChange)="setChecked('prop1', $event)" name="prop1" />
with the two public methods defined in the component class:
public isChecked(propName: string): boolean {
return this.myobj[propName] === "Y";
}
public setChecked(propName: string, value: boolean): void {
this.myobj[propName] = value ? "Y" : "N";
}
Upvotes: 2