Using ngIf for binding

Trying to bind values based on conditions specified in *ngIf. However, when using the && operator within *ngIf, it seems to be behaving mysteriously.

Sample Code:

       
        <div *ngIf="days.sunday == true">
          <p class="circle ml-3">Sun</p>
        </div>
        <div *ngIf="days.monday == true">
          <p class="circle ml-2">Mon</p>
        </div>
        <div *ngIf="days.tuesday == true">
          <p class="circle ml-2">Tue</p>
        </div>
        <div *ngIf="days.wednesday == true">
          <p class="circle ml-2">Wed</p>
        </div>
        <div *ngIf="days.thursday == true">
          <p class="circle ml-2">Thu</p>
        </div>
        <div *ngIf="days.friday == true">
          <p class="circle ml-2">Fri</p>
        </div>
        <div *ngIf="days.saturday == true">
          <p class="circle ml-2">Sat</p>
        </div>

The above conditions are functioning correctly, displaying the values as intended.

   
   <div *ngIf="days.sunday == true && days.monday == true  && days.tuesday  == true && days.wednesday  == true && 
   days.thursday  == true && days.friday == true &&  days.saturday == true">
            <p class="circle ml-2">Everyday</p>
                </div>

In the above condition, attempting to display Everyday only if all conditions are met. However, currently getting displayed as sun mon tue wed thu fri sat Everyday

Answer №1

Implement an If/Else template in Angular

  • Condition to check if all days are true - If true, display only Everyday
  • If false, display respective days based on their conditions

<!-- If block for "Everyday" -->
<div *ngIf="days.sunday && days.monday && days.tuesday && days.wednesday && 
    days.thursday && days.friday && days.saturday; else elseBlock">
    <p class=" circle ml-2 ">Everyday</p>
</div>

<!-- Else block for other days "Sun, Mon, etc..." -->
<ng-template #elseBlock>
    <div *ngIf="days.sunday">
        <p class="circle ml-3">Sun</p>
    </div>
    <div *ngIf="days.monday">
        <p class="circle ml-2">Mon</p>
    </div>
    <div *ngIf="days.tuesday">
        <p class="circle ml-2">Tue</p>
    </div>
    <div *ngIf="days.wednesday">
        <p class="circle ml-2">Wed</p>
    </div>
    <div *ngIf="days.thursday">
        <p class="circle ml-2">Thu</p>
    </div>
    <div *ngIf="days.friday">
        <p class="circle ml-2">Fri</p>
    </div>
    <div *ngIf="days.saturday">
        <p class="circle ml-2">Sat</p>
    </div>
</ng-template>

Note

days.sunday === true is the same as using days.sunday as it is a boolean value

Answer №2

When faced with a certain situation, it is important to consistently follow the same routine every day.

<div *ngIf="days.sunday == true && days.monday == false && days.tuesday == false &&
days.wednesday == false && days.thursday == false && days.friday == false &&
days.saturday == false">
  <p class="circle ml-3">Sun</p>
</div>
...

Answer №3

When using *ngIf, there is no built-in "else" functionality. This means that if all conditions are met, it will enter every branch.

If you want to avoid this behavior, you will have to adjust your conditions.

This characteristic is not unique to *ngIf and Angular.

Answer №4

If my understanding is correct, you are looking to display the days that are evaluated as true, or 'Every day' if all are true.

In your specific component:

everyday = this.days.sunday === true && this.days.monday === true && 
    this.days.tuesday === true && this.days.wednesday === true && 
    this.days.thursday === true && this.days.friday === true && this.days.saturday === true;

Then in the corresponding view section:

<div *ngIf="days.sunday === true && everyday === false">
   <p class="circle ml-3">Sun</p>
</div>
... and so on.
<div *ngIf="everday === true">
   <p class="circle ml-3">Every day</p>
</div>

Answer №5

Here's a code snippet that should function as expected

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  days = { sunday: true, monday: true, tuesday: true, wednesday: true, thursday: true, friday: true, saturday: true };

  isEveryDay() {
    let everyday = true;
    for (let key in this.days) {
      let value = this.days[key];
      if (!value) {
        everyday = false;
        break;
      }
    }
    return everyday;
  }
}

<hello name="{{ name }}"></hello>
<div *ngIf="!isEveryDay()">
    <div *ngIf="days.sunday == true">
        <p class="circle ml-3">Sun</p>
    </div>
    <div *ngIf="days.monday == true">
        <p class="circle ml-2">Mon</p>
    </div>
    <div *ngIf="days.tuesday == true">
        <p class="circle ml-2">Tue</p>
    </div>
    <div *ngIf="days.wednesday == true">
        <p class="circle ml-2">Wed</p>
    </div>
    <div *ngIf="days.thursday == true">
        <p class="circle ml-2">Thu</p>
    </div>
    <div *ngIf="days.friday == true">
        <p class="circle ml-2">Fri</p>
    </div>
    <div *ngIf="days.saturday == true">
        <p class="circle ml-2">Sat</p>
    </div>
</div>
<div *ngIf="isEveryDay()">
    <p class="circle ml-2">Everyday</p>
</div>

Check out the demo here

Answer №6

component.html

<div *ngFor="let day of days">
         <div *ngIf="day == 'sunday'">
          <p class="circle ml-3">Sun</p>
        </div>
        <div *ngIf="day == 'monday'">
          <p class="circle ml-2">Mon</p>
        </div>
        <div *ngIf="day == 'tuesday'">
          <p class="circle ml-2">Tue</p>
        </div>
        <div *ngIf="day == 'wednesday'">
          <p class="circle ml-2">Wed</p>
        </div>
        <div *ngIf="day == 'thursday'">
          <p class="circle ml-2">Thu</p>
        </div>
        <div *ngIf="day == 'friday'">
          <p class="circle ml-2">Fri</p>
        </div>
        <div *ngIf="day == 'saturday'">
          <p class="circle ml-2">Sat</p>
</div>
 </div>

 <div *ngIf="alldays == true">
    <p class=" circle ml-2 ">Everyday</p>
</div>

component.ts:

  alldays = true;
   days: any = ['sunday', 'monday', 'tuesday ', 'wednesday', 'thursday', 'friday', 'saturday' ];

Depending on the value of the alldays flag, you can choose to display or hide certain elements as needed.

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

What steps can be taken to implement jQuery within an Angular 15 npm package?

In my development process, I often create my own npm packages using Angular and Typescript. One of the packages I am currently working on is a PDF viewer service, which includes a file named pdf-viewer.service.ts with the following code: import { Behavior ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

Can auto-import be configured in WebStorm without using double dots?

Is it feasible to configure WebStorm for automatic import of modules/Component/components/MyComponent instead of using ../MyComponent? ...

Component's mocking service is being ignored

I am currently exploring how to simulate a service (specifically one that makes http calls) in order to test a component. @Component({ selector: 'ub-funding-plan', templateUrl: './funding-plan.component.html', styleUrls: ['. ...

Arrange two Angular 2 divs in a single row, with one positioned below the

Good Evening, I have a project in angular and I need help with styling. Specifically, I have 3 divs - card, table, and map. I want the card and table to be in the same row, and the map to be below them with double the size. The top left should have item in ...

Tips for preventing the rxjs error "TypeError: Cannot read properties of undefined" in the Angular framework

When I try to open the page in Angular, I encounter this error: core.mjs:6485 ERROR TypeError: Cannot read properties of undefined (reading 'getDocumentContent') In my Angular component, I have an observable like this: selectedDocument$ = this.s ...

Using a Jasmine spy to monitor an exported function in NodeJS

I've encountered difficulties when trying to spy on an exported function in a NodeJS (v9.6.1) application using Jasmine. The app is developed in TypeScript, transpiled with tsc into a dist folder for execution as JavaScript. Application Within my p ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

Issue with upgrading node from 12v to 16v: Trying to access a property that does not exist, specifically 'splice', within a circular dependency in module exports

After upgrading the node version from 12 to 16, we encountered a debugging console error. The 'Promises' are failing to resolve following this error, leading to the termination of further execution. (node:28112) Warning: Accessing non-existent p ...

Connect a datetime-local typed input to a Date attribute in Angular 2

Can a property of type Date in a component be bound to an HTML5 input with the type attribute set as datetime-local? For example, I have a component with the following property: public filterDateFrom: Date; And in my template, I am trying to bind this p ...

Angular - Automatically populate nested form with provided data

Here is the link to my StackBlitz project: https://stackblitz.com/edit/create-eez7wi?file=app/app.component.ts I am facing an issue where when I load the resources, it fills all fields except for the skill if more than 1 is entered. setResourceDTOS() { ...

The Environment variable in React Native is not functioning when utilizing TypeScript

After installing the react-native-dotenv library, I followed the instructions outlined in the TypeScript guide. I then created a .env file with the following contents: MARVEL_API = <url> MARVEL_PUBLIC_KEY = <public-key> MARVEL_PRIVATE_KEY = &l ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...

Master your code with Rxjs optimization

Looking at a block of code: if (this.organization) { this.orgService.updateOrganization(this.createOrganizationForm.value).subscribe(() => { this.alertify.success(`Organization ${this.organization.name} was updated`); this.dialogRef.close(true ...

Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays: [ ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338], ["2000-01-01", "<a href="/ ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Display embedded ng-template in Angular 6

I've got a template set up like this <ng-template #parent> <ng-template #child1> child 1 </ng-template> <ng-template #child2> child 2 </ng-template> </ng-template> Anyone know how t ...

Do you think it's important to include a maxlength validation message for an input field in Angular?

Utilizing the maxlength attribute on a form field not only enables Angular's default validation, it also restricts input beyond the specified length from being typed into the text box. So, does this imply that displaying an error message for violating ...

The TypeScript error occurs when trying to set the state of a component: The argument 'X' cannot be assigned to the parameter of type '() => void'

When I attempt to call setState, I encounter a TypeScript error. Here is the code snippet causing the issue: updateRequests(requests: any, cb:Function|null = null) { this.setState( { requests: { ...this.state.requests, ...

Mapped types: Specify mandatory properties depending on whether an array of identical objects includes a specific string value

Can an object property be set to required or optional based on the presence of a specific string in an array within the same object? type Operator = "A" | "B" type SomeStruct = { operators: Operator[]; someProp: string; // this should be ...