When the boolean is initially set to false, it will return true in an if statement without using

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.

Answer №1

I agree with @oreofeolurin's perspective. It seems that the issue at hand is not specific to Angular, but rather a JavaScript/TypeScript problem related to using `self` instead of `this`.

Check out this Plunker example I put together to illustrate the issue: https://plnkr.co/edit/SzNQyHvyLVjfN9Fm6GER?p=preview

 <div class="divClass" (click)="onClick($event)">Click me</div>
 <div>Clicks: {{clicks}} </div>


clicks = 0;

  guardFirst : boolean;
  guardSecond : Boolean;

  constructor() {
    this.guardFirst = false;
    this.guardSecond = false;
  }

  onClick( ev : MouseEvent ) {

    this.clicks++;

    if (this.guardFirst) {
      if (this.guardSecond) {
        alert("hi");
      }
      this.guardSecond = true;
    }
    this.guardFirst = true;
  }
}

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

Utilize a method categorization while implicitly deducing parameters

Scenario In my project, I have a unique class setup where methods are passed in as a list and can be called through the class with added functionality. These methods are bound to the class (Foo) when called, creating a specific type FooMethod. class Foo { ...

Troubleshooting issue with TypeScript: Union types not functioning correctly when mapping object values

When it comes to mapping object values with all primitive types, the process is quite straightforward: type ObjectOf<T> = { [k: string]: T }; type MapObj<Obj extends ObjectOf<any>> = { [K in keyof Obj]: Obj[K] extends string ? Obj[K] : ...

Utilizing Azure Active Directory for Authentication in Angular 13 and .NET Core Web API

I've set up a .NET CORE 6 Api as the backend and an Angular 13 frontend. I'm currently facing authentication issues with Angular using msal to call the protected .NET Core API, specifically the weatherforcast template. While I can successfully au ...

Angular8: Stay Updated with Real-Time Data Refreshment

I've implemented code in my app.component to retrieve all users. I'm facing an issue where if I have two windows open and perform any CRUD actions, the second window displays outdated data. To address this, I am attempting to refresh the page ev ...

Adding a class to the current li element without affecting its siblings in Angular 2

I am dealing with a structure that looks like this: <div> <ul> <li> <ul> <li>Option 1</li> <li>Option 2</li> <li>Option 3</l ...

Classname fails to modify the base style of the AppBar

Struggling to modify the appearance of the AppBar component by utilizing the className attribute, however, the .MuiAppBar-root class consistently takes precedence. const useStyles = makeStyles((theme: Theme) => ({ appBar: { backgroundColor: &apos ...

Trigger the React useEffect only when the inputed string matches the previous one

Currently, I am in the process of creating my own custom useFetch hook. export const useFetch = <T extends unknown>( url: string, options?: RequestInit ) => { const [loading, setLoading] = useState(false); const [error, setError] = ...

Designing a Tombstone with TypeScript

In TypeScript, I have certain values that are only necessary within the type system and not at runtime. I am seeking a way to void these values without losing their type information. The function bury illustrated below is intended to replace the actual v ...

An entire line of boxes has been checked off

Currently, I am working on adding an additional column with checkboxes to the Mat table example. However, I noticed that when I click on one checkbox in a column, the checkboxes in other columns also get selected. How can I implement this so that only th ...

Submit information by utilizing' content-type': 'application/x-www-form-urlencoded' and 'key': 'key'

Attempting to send data to the server with a content-type of 'application/xwww-form-urlencode' is resulting in a failure due to the content type being changed to application/json. var headers= { 'content-type': 'applica ...

The input feature in the Angular 4 Library allows users to easily

Hello everyone, I could really use some assistance with a problem I am facing. For some reason, I can't seem to make it work properly. I suspect that there might be an issue with the syntax I am using. Currently, I am in the process of developing Ang ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

Personalize the Ag-Grid Status Bar to your liking

Currently utilizing Ag-Grid Enterprise, Version 19 ("ag-grid-angular": "19.0.0", "ag-grid-community": "19.0.0", "ag-grid-enterprise": "19.0.0") in conjunction with Angular 4. There is a specific need to customize the status bar of the grid and add an add ...

Help! My Angular CLI version 8.2.2 is displaying squares instead of the Font-awesome icons

I successfully added Font Awesome using the command npm install --save font-awesome angular-font-awesome from https://www.npmjs.com/package/angular-font-awesome. After linking it in my angular.json file: "styles": [ "src/styles.css", "node_modu ...

`The dilemma of z-index in a dropdown menu nested within an animated card`

Having an issue that I have attempted to simplify in this StackBlitz example (the actual project is created with Angular components and Bootstrap, etc.): https://stackblitz.com/edit/angular-bootstrap-4-starter-njixcw When incorporating a dropdown within ...

Having trouble retrieving mobiscroll instance in Angular with Ionic

I'm facing an issue with accessing the instance of my mobiscroll widget in Angular 4 with Ionic Framework. Despite following all the correct steps, the actual widget won't get selected. Below is the code for the widget: <mbsc-widget [options ...

The type '{ }' does not include the properties 'params', 'isExact', 'path', 'url' from the 'match<Identifiable>' type

Currently, I am utilizing react router and typescript in order to extract the id variable from a route for use in a component. However, typescript is raising an issue: The type '{}' lacks the following properties found in type 'match' ...

What is the best way to create and manage multiple collapsible Material-UI nested lists populated from an array with individual state in React

In my SideMenu, I want each list item to be able to expand and collapse independently to show nested items. However, I am facing the issue of all list items expanding and collapsing at the same time. Here is what I've attempted: const authNavigation ...

npm installation raises concerns about unmet peer dependencies despite them being already satisfied

I recently completed an upgrade to the final release of angular 2 from rc-6. Transitioning through different beta/rc versions was smooth and without any complications. My package.json dependencies include: "dependencies": { "@angular/common": "2.0.0" ...

What is the process for activating shift key - multi-selection in the PrimeNG pick list?

I'm currently utilizing the prime ng pick list from the PrimeNG API located at: https://www.primefaces.org/primeng/#/picklist An issue I've encountered is that the picklist doesn't support multiple selections. For instance, in this example ...