Converting Boolean values from backend data to strings using TypeScript in Angular

A value is being returned from my backend as a boolean (true/false) and I need to display it 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'];
}

The above code snippet is written in my TypeScript file to handle the condition, however it seems to be not functioning correctly.


Answer №1

Define a variable within a class and then, once the data has been retrieved,

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

Utilize this variable in the HTML code:

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

Alternatively, embed it directly into the HTML code:

<span>
  Status : {{data.is_active ? 'active' : 'inactive'}}
</span>

Answer №2

To easily show text depending on a boolean value without using additional typescript code, you can directly include the conditional statement in your HTML as shown below:

Check out the live demo here

Here's an example:

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

Answer №3

Wondering how to make your code work effortlessly? Try out this simple solution below...

Whether it's a Boolean value or a string, this piece of code will handle it smoothly. If the value is Boolean, it will use data['is_active']. And if it's a string, it will fallback to data['is_active'] === 'true'.

Keep coding and stay happy! :)

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

Answer №4

Feel free to give this a shot

if( Boolean(input['is_active']) === true){
       input['is_active'] = 'active';
            current.isActive = input['is_active'];
        }else
        {
            input['is_active'] = 'inactive';
            current.isActive = input['is_active'];
        }

Answer №5

After obtaining my backend information by ID, I created a variable called "status" in typescript

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

                    }

In the HTML section, I utilized {{status}} to convert my boolean value into a string

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to prevent the ng2-bootstrap datepicker div from being displayed when the user clicks outside of it?

I'm utilizing an ng2-datepicker to collect a user's date of birth during the registration process. To adhere to the requirement of displaying it as a popup, I have enclosed the datepicker within a div that is displayed when the user clicks a butt ...

What is the best way to position three DIVs next to each other within another DIV while aligning the last DIV to the right?

I need help formatting a simple list item with three DIVs. The first DIV should be left justified, the second should be able to grow as needed, and the third should be right justified. I currently have them stacked side by side, but can't get the last ...

Top Choice UI Component for Angular 2 Development

As a newcomer to Angular2, I am in the process of building an application from scratch. This application will require extensive use of controls such as Scheduler, Grids, Charts, and others. After researching on Google, I have come across Syncfusion, Kend ...

Load the data of the app component in Angular 2 once a user has successfully logged in on a different

I am having an issue with my app.component where the user's email is not showing in the top menu immediately after logging in and being redirected to the data list page. The email only appears after I reload the page. What I need is for the email to ...

What is preventing the lighter and bolder font weights from functioning properly?

I am currently developing an app using Ionic and I have chosen to include the custom font 'Rubik'. Despite importing both 'lighter' and 'bolder' font weights, they do not seem to apply - whenever I set the style, it defaults t ...

Using forEach with switch cases in Angular5 (TypeScript)

I am trying to work with a basic array of languages and a switch function, but I am having trouble using the forEach method on the cases. It would be really helpful as there are numerous languages in the world! ;) public languages = ["en", "de"]; public s ...

Creating a secure connection on localhost with angular dart webdev: A step-by-step guide

Currently, I am developing a web application using Angular Dart. One issue I encountered is accessing the user's location feature through geolocation, as browsers like Chrome require HTTPS for this functionality. When deploying the web application, th ...

When a user clicks on the download link, it redirects them to the homepage in Angular

When using Angular 6 and the downloadFile method to download an Excel sheet from the WebAPI, everything runs smoothly. A dialog box opens up asking to save the file on the drive, but then it unexpectedly navigates me back to the home page. This redirects ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...

Retrieve the file from the REST API without using the window.open method

I'm looking for a method to download files from an API without using window.open(). I want the download process to start immediately upon calling the API. Currently, I am downloading an .xls file generated by a REST API using window.open() API Endpo ...

Tips for populating all the ionic form fields using speech recognition technology

In the process of developing an Ionic 4 application, I am faced with a challenge where I need to fill in multiple form fields using the Ionic speech-recognition plugin. Currently, I am only able to populate one field at a time. What I am looking for is a w ...

Activate the location feature within an Ionic application

When using the function this.geolocation.getCurrentPosition() to retrieve the user's latitude and longitude, I encounter issues when the location setting is turned off. It does not provide any response in such cases. I am seeking a way to notify the u ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

What is the most efficient method for sorting a complex JSON object?

I have a JSON object with multiple nested levels: { "myJson": { "firstGroup": { "0": [ { "month": 1.0, "amount": 1.7791170955479318, ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

Extending a Typescript interface to include the functionality of two different component

When implementing this code snippet, a user will find an output of an <input> element, which works flawlessly: interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> { error?: FieldError; icon?: string; id: string; reg ...

Setting default values on DTO in NestJS can be done by using the DefaultValue decorator provided

import { IsString, IsNumber, IsOptional, IsUUID, Min, Max } from 'class-validator'; import { Transform } from 'class-transformer'; export class QueryCollateralTypeDto { @Transform(({ value }) => parseInt(value)) @IsNumber() @I ...

Is it possible to run NestJS commands without relying on npx?

I recently installed nestjs using npm, but I encountered an issue where it would not work unless I added npx before every nest command. For example: npx nest -v Without using npx, the commands would not execute properly. In addition, I also faced errors ...

Steps for TS to infer types on interfaces

Incorporated in my React application is an object that I devised. Within this object, there is the following definition for Props: type Props = { message: MessageTypes | MessageImgTypes; showTimeStamp: boolean; } If we assume that MessageTypes consists o ...

The tooltip popup does not appear within the nz-tabs

Looking to enhance my two tabs with an info icon preceding the tab text, along with a tooltip popup that appears when hovering over the icon. Despite trying different methods, I have yet to achieve the desired outcome. <nz-tabset [nzLinkRouter]=&qu ...