0

My backend throws a boolean value (true/false) which have to display as a string (active/inactive).

if (data['is_active'] == true) {
  data['is_active'] = 'active';
  this.is_active = data['is_active'];
} else {
  data['is_active'] = 'inactive';
  this.is_active = data['is_active'];
}

this is the above code written in mt typescript to check the condition, but it is not working


3
  • this.is_active="active" ? Commented Nov 12, 2019 at 7:45
  • Have you tried the solution? Commented Nov 12, 2019 at 19:51
  • Yes, I have posted my answer below. Commented Nov 13, 2019 at 9:51

5 Answers 5

1

Create a variable in class, and then after fetching the data,

this.status = data['is_active'] ? 'active' : 'inactive'

and use this variable inside html:

<span>Status : {{this.status}}</span>

OR directly in html:

<span>
  Status : {{data.is_active ? 'active' : 'inactive'}}
</span>
Sign up to request clarification or add additional context in comments.

Comments

0

If you just want to display text based on boolean value, no need to add anything in typescript, you can add condition in html:

Working Demo

Try like this:

Status : {{data.is_active ? 'active' : 'inactive'}}

Comments

0

Just put below line of code, will work like a charm... Here if its return Boolean data['is_active'] handles it and if its of type string so added fallback data['is_active'] === 'true'.

Happy coding ... :)

data['is_active'] = (data['is_active'] || data['is_active'] === 'true') ? 'active' : 'inactive';

1 Comment

you should explain your ternary expression so the OP understands why your code might work.
0

you can try this

if( Boolean(data['is_active']) === true){
       data['is_active'] = 'active';
            this.is_active = data['is_active'];
        }else
        {
            data['is_active'] = 'inactive';
            this.is_active = data['is_active'];
        }

Comments

0

I have fetched my backend data using ID, Then I assigned a variable as status in typescript

 if (this.user['is_active'] == true) {
                        this.status = 'active';
                    } else {
                        this.status = 'inactive';

                    }

where in html, I used {{status}} to display my boolean value into string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.