I am trying to check a Boolean values truthiness in Angular HTML, and getting an odd result. After reading this SO post I thought I understood what was happening. I expected to be able to use the === operator, but as my last example below shows, that does not return the correct result.
StackBlitz example of my code
The output states of my code above:
nothing selected, but default val is false
create new: false
double eq isCreateNew==false: true
string isCreateNew=='false': false <----- unexpected
obj isCreateNew===false: true
set to true create new: true
double eq isCreateNew==false: false
string isCreateNew=='false': false
obj isCreateNew===false: false
set to false
create new: false
double eq isCreateNew==false: false <----- unexpected
string isCreateNew=='false': true
obj isCreateNew===false: false <----- unexpected
As per the type conversion rules, a string 'false' does not get converted to the boolean false. This means that
false == 'false' // It is indeed false
So this should not be unexpected, it is the expected result.
Now you might ask why it returns true when you set isCreateNew to false. The problem is actually in your code. Your radio buttons are not setting the value to boolean false or true rather it is setting it to a string. To set it to a boolean, you need to use square brackets.
<mat-radio-button class="example-radio-button" [value]="true">set true</mat-radio-button>
<mat-radio-button class="example-radio-button" [value]="false">set false</mat-radio-button>
Another way to tell your value is not being set properly is by your ngModel. If you set isCreateNew to false in your component, it should set check the false radio button. Since your values are strings, this will not happen. Once you add the square brackets, you can see that the false radio button gets checked.
Only an empty string equals `false' in JS. So, the expected result is that
string isCreateNew=='false': false
always. You can easily check this in the browser console.
Then, you don't use square brackets when binding the mat-radio-button value property. In this case, the passed value is not evaluated as JavaScript. As a result, the value of your mat-radio-button elements is a string. Not a boolean. Use square brackets to resolve other issues.
<mat-radio-group class="example-radio-group" [(ngModel)]="changeAE">
<mat-radio-button class="example-radio-button" [value]="true">set true</mat-radio-button>
<mat-radio-button class="example-radio-button" [value]="false">set false</mat-radio-button>
</mat-radio-group>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With