angular convert boolean to yes no

How to Convert Boolean to "Yes" or "No" in Angular

As an Angular developer, you may encounter a situation where you need to convert a boolean value into a "Yes" or "No" string. This can be done using Angular Pipes.

Using the Built-in Angular Boolean Pipe

The easiest way to convert a boolean value to "Yes" or "No" is to use the built-in Angular boolean pipe. This pipe accepts a boolean value and returns "Yes" if the value is true and "No" if the value is false.


<div>Is Active: {{ isActive | lowercase }}</div>
  • | lowercase is used to convert the output string to lowercase.

Using a Custom Pipe

If you need more control over the output string, you can create a custom pipe that will convert a boolean value to any string of your choice. To create a custom pipe, you need to use the Angular CLI command ng generate pipe.


ng generate pipe boolean-to-yes-no

This command will create a new file named boolean-to-yes-no.pipe.ts in the app/boolean-to-yes-no folder.

Open the boolean-to-yes-no.pipe.ts file and update the code as follows:


import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'booleanToYesNo'
})
export class BooleanToYesNoPipe implements PipeTransform {

  transform(value: boolean): string {
    return value ? 'Yes' : 'No';
  }
}

The transform function accepts a boolean value and returns "Yes" if the value is true and "No" if the value is false.

Now that we have created our custom pipe, we can use it in our component template:


<div>Is Active: {{ isActive | booleanToYesNo }}</div>

This will output "Yes" if the isActive value is true and "No" if the isActive value is false.

Conclusion

In conclusion, converting a boolean value to "Yes" or "No" in Angular can be done using either the built-in boolean pipe or by creating a custom pipe. By using pipes, you can easily format your data to fit your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe