My Angular component contains a component-level boolean variable and an onClick event. Here's what the HTML file looks like:
<div class="divClass" (click)="onClick($event)"></div>
The relevant code from the TypeScript file is as follows:
export class myComponent implements OnInit {
guardFirst : boolean;
guardSecond : Boolean;
constructor(...) {
this.guardFirst = false;
this.guardSecond = false;
}
onClick( ev : MouseEvent ) {
if (this.guardFirst) {
if (this.guardSecond) {
console.log("first guard: " + this.guardFirst + "; second guard: " + this.guardSecond);
// the logic takes place here
}
this.guardSecond = true;
}
this.guardFirst = true;
}
}
I've modified the actual code for privacy reasons, but the structure remains the same. Despite expecting the logic and console logging not to happen until the third click in the div, it occurs on the first click. The console logs false for both variables, even though it has passed two if statements that should return false based on conventional language behavior. After thorough debugging and value checking, I made a change to the code:
onClick( ev : MouseEvent ) {
if (this.guardFirst == true) {
if (this.guardSecond == true) {
console.log("first guard: " + this.guardFirst + "; second guard: " + this.guardSecond);
// the logic takes place here
}
this.guardSecond = true;
}
this.guardFirst = true;
}
This observation led me to realize that booleans without a value equivalence statement return true if they are not null or undefined. Both false and true values, as long as a value is assigned, return true. Although my code had booleans as both primitives and objects, this behavior cannot be attributed to that. Testing a similar scenario on jsfiddle in TypeScript without Angular produced the expected result of returning false when the value was false, regardless of using ==.
Can someone shed light on this phenomenon? What is causing it? It appears to be peculiar to Angular - is this accurate? Does this behavior consistently occur in all Angular projects, or is there something amiss in my setup? Is this intentional, and if so, why did the developers choose this approach? If not intentional, what could be causing it?
Thank you in advance.
EDIT: Fixed the self/this typo. To the individual who voted to close the question, kindly share your reasoning with a comment explaining how it can align with SO guidelines.