Marc El Bichon
Marc El Bichon

Reputation: 407

Typescript with Angular 2 issue on boolean

I'm facing a strange issue while filling a model from a API result.

My model looks like this:

import {Company} from './../api/odata/data/Company';

export class MyModel {
...
isEnabled = false;
....
    constructor(data: Company= null) {
        try {
            this.isEnabled = !data.isDisabled;
            ...
        }
        ...
}

When I fill the data model, if data.isDisabled equals false, this.isEnabled should be true, but it's returning false...

enter image description here

enter image description here

Upvotes: 0

Views: 191

Answers (1)

Angular Dev
Angular Dev

Reputation: 4916

data.isDisabled is a string buddy. You could convert it to a boolean in multiple ways. But I am curious where the data came from in the first place.

If there is no way to ensure data.isDisabled comes as a boolean you could do two things.

1- Check what the strings value is and based on that return a boolean.

this.isEnabled = data.isDisabled === 'true' ? false : true

2- Or use eval, which I would not recommend

this.isEnabled = eval(data.isDisabled);

3- Backwards compatible solution, best of all three

This will even work if isDisabled is an actual boolean.

this.isEnabled = !JSON.parse(data.isDisabled);

See more on string to boolean conversion here

Upvotes: 3

Related Questions