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

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Converting a stringified array object to an object using Expressjs

When working with Angular, I am sending stringified data using FormData. Here is an example: this.formData.append('data', JSON.stringify(this.collections)) Now my challenge is converting this string back to an object in my Express backend. The d ...

Tips for eliminating the gap between digits and symbols in an OutlinedTextField within the Material Ui framework

Using material Ui OutlinedTextField with the code snippet below import { List, styled, Switch, TextField, Theme, withStyles } from '@material-ui/core'; export const OutlinedTextField = withStyles((theme: Theme) => ({ root: { '& ...

Transform the subscription into a string

When I use the http method to retrieve a single user, the output logged in the console looks like this: this.usersService.getOneUser().subscribe(data => { console.log(data) }); email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Selecting logic depending on the request body in NestJS

Currently, my controller looks like the following: @Controller("workflow") export class TaskWorkflowController { public constructor( private readonly jobApplicationActivityWorkflow: JobApplicationActivityService ) {} @Post("/:job- ...

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Error in Typescript Observable when using .startWith([])

I encountered the TypeScript error below: Error:(34, 20) TS2345: Argument of type 'undefined[]' is not assignable to parameter of type 'number | Scheduler'. Type 'undefined[]' is not assignable to type 'Scheduler& ...

Angular 6 form input value displays incorrectly after dynamically closing a tab

After adding a child-component with a form inside a tab, I noticed that when I closed the tab, the child-component form value was changed to the deleted tab. However, the span value remained correct. It's quite strange - could this be a bug? Check ou ...

"Unlock the power of remote-redux-devtools in NgRx: A step-by-step guide

Currently, I am utilizing NgRx in an Angular NativeScript project for Android and iOS apps, and it is proving to be quite effective. However, one aspect that concerns me is the inability to use @ngrx/store-devtools and the Redux DevTools Chrome extension d ...

Forwarding routes with Angular Router

My server has specific mappings for different URLs: / serves an Angular application with routing capabilities /admin serves a Django control panel for staff database updates /api and /api/... serve REST endpoints to handle queries and return JSON data I ...

The method mockImplementation cannot be found on the busboyConstructor object

Despite extensive research, I have yet to find a solution to my problem. Whenever I attempt to mock busboy in my project using jest, I keep encountering an error stating that mockImplementation (and mockRestore) is not a function. import * as Busboy from ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

Encountering an issue with Ionic forms: Error message NodeInjector: NOT_FOUND [ControlContainer] is displayed

I have developed an Ionic application with a form. Everything was working fine until I integrated the form group and related elements into my code. Since then, I've been encountering this error: core.js:6260 ERROR Error: Uncaught (in promise): Erro ...

Having trouble accessing props on children in TypeScript while using React.Children.toArray?

When using React.Children.toArray in Typescript, the props object on children is not detected. In order to address this issue, I am currently using any[] instead of ReactChild[], as props are not recognized on a array item when using the latter. Can someon ...

The tRPC setData hook is limited in its ability to access all data necessary for optimistic UI updates

As I integrate mutations using tRPC and React Query to optimistically update my UI upon adding a new item, I've encountered an issue. The problem lies in the query I'm updating, which requires specific properties like auto-generated IDs or datab ...

Error encountered during the production build of Angular 2. No issues reported during development phase

During development, I can successfully run the code below. However, when I deploy to production, I encounter the following errors: node_modules/@angular/common/src/pipes/async_pipe.d.ts(39,38): error TS2304: Cannot find name 'Promise'. node_modu ...

Enhancing the internal styling of ngx-charts

While working on the ngx-charts Advanced Pie Chart example, I noticed that the numbers in my legend were getting cut off. Upon inspecting the CSS, I discovered that a margin-top of -6px was causing this issue: https://i.stack.imgur.com/oSho1.png After so ...

"How to automatically populate an input field with a value when the page loads in an

I need assistance with setting the input value to 1 when the page is loaded, but for some reason, it remains empty. Can someone help me troubleshoot this issue? <tr *ngFor="let item of cartItems; let i=index"> <td class="cart_pr ...

Learn how to use the rendertron middleware in Node.js Express to redirect all routes to the original Angular app

Currently, I am working on creating a rendertron middleware using nodejs to determine when to utilize pre-rendered content and when to use the original application. However, I am facing challenges in redirecting to my usual Angular app using fetch or any o ...

Using `it` with accessing class members

When testing whether a specific object/class is correctly wired up, I often utilize it.each to prevent writing repetitive tests. The issue arises when the type of the object doesn't have an index signature, requiring me to cast it to any for it to fun ...