Adjusting the value of a mat-option depending on a condition in *ngIf

When working with my mat-option, I have two different sets of values to choose from:

tempTime: TempOptions[] = [
    { value: 100, viewValue: '100 points' },
    { value: 200, viewValue: '200 points' }
  ];

tempTimesHighNumber: TempOptions[] = [
    { value: 1000, viewValue: '1000 points' },
    { value: 2000, viewValue: '2000 points' }
  ];

In order to create a conditional statement in my HTML based on two specific variables:
public SentDate;
public CurrentDate;

I'm extracting these variables from a datepicker. The goal is to display the tempTime values in the mat-options if the dates are equal, and show the temptimesHighNumber values if they are not.

This is what I attempted:

<mat-form-field>
      <mat-label>Tally up that score!</mat-label>
      <mat-select
        [(value)]="selectedTempTime"
      >
        <ng-container>
          <mat-option
            *ngIf="checkConditionSentDate === checkConditionCurrentDate"
            [value]="option.value"
            *ngFor="let option of tempTimes"
            >{{ option.viewValue }}</mat-option
          >
          <mat-option
            [value]="option.value"
            *ngFor="let option of tempTimesIfNotTodaysDate"
            >{{ option.viewValue }}</mat-option
          >
        </ng-container>
      </mat-select>
    </mat-form-field>

The error message received is:

Can't have multiple template bindings on one element. Use only one attribute prefixed with * ("heckConditionSentDate === checkConditionCurrentDate"
What would be the correct approach for utilizing *ngIf, or am I approaching this incorrectly?

Answer №1

To enhance the display of each mat-option, you can utilize ng-container and apply *ngIf on the ngContainer as shown below:

    <ng-container *ngIf="checkConditionSentDate === checkConditionCurrentDate">
      <mat-option [value]="option.value"
                  *ngFor="let option of tempTimes">{{ option.viewValue }}
      </mat-option>
    </ng-container>
    <ng-container *ngIf="otherCondition">
      <mat-option
              [value]="option.value"
              *ngFor="let option of tempTimesIfNotTodaysDate"
      >{{ option.viewValue }}</mat-option
      >
    </ng-container>

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

Tackling the white-source security problem in npm libraries

A security advisory from White-source has identified high vulnerability issues with certain libraries used in your repository, specifically with yargs-parser: 1. build-angular-0.13.8.tgz (Root Library) node-sass-4.11.0.tgz sass-graph-2.2 ...

Exploring the latest features of Angular 13 alongside a useful NPM module that utilizes

I have encountered an issue with my date-picker module for Angular that involves importing moment.js. The problem arises when I import the NPM package moment-es6, which imports moment.js in the following way: import * as moment from "moment"; ...

Why won't my Angular 2 *ngIf display until the function finishes?

Here is the code snippet that I am dealing with... // Pug Template .notification-header-area.layout-row.layout-align-center-center( *ngIf="notification.message != null", class="{{notification.color}}" ) // Inside angular component private onNotificationS ...

Only the (click) event is functional in Angular, while the (blur), (focus), and (focusout) events are not functioning

I have a unique HTML element as shown below <div (hover)="onHover()" (double-click)="onDoubleClick()" (resize)="resize()" (dragend)="dragEnd()"> These 4 functions are designed to display information onHover ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

An error was encountered: The CommonModule type does not contain the 'ɵmod' property. This issue is occurring at the getNgModuleDef function in the core.js file

After transferring my project to Amazon Workspace and updating Angular to version 14.2.6, I encountered an issue where I received the error message: "Uncaught Error: Type CommonModule does not have 'ɵmod' property." This error did not occur on m ...

The defineProps<SomePropType>() method is not rendering the props as expected

I have various components, with a parent element where I attempted to pass props using the syntax defineProps<{}>(). The setup is simple, I have a types.ts file at the root level, a parent Vue file (referred to as CardItem), and multiple components. ...

Issue encountered while submitting form data to API endpoint using Angular framework

Having trouble posting form data to a web api using a service that consistently returns a 404 bad request error. The service method looks like this: postIncidents(): Observable<any> { return this.http.post<any>(this.serviceApiUrl, {}) ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

Encountering an Uncaught TypeError when attempting to set properties of null with useRef

I've been working on an app that requires access to the user's device camera in order to display live video on the screen. I've managed to achieve this by utilizing a video HTML Object and setting the media stream as its srcObject. Everythin ...

determining the properties of a given data type

I am currently working with a type that I have obtained from a third party source. My goal is to determine the type of a specific property within that type, using TypeScript. For example: type GivenType = { prop: string; } type desiredType = <&l ...

What is the best way to incorporate CSS from node_modules into Vite for production?

I have a TypeScript web application where I need to include CSS files from NPM dependencies in index.html. Here is an example of how it is done: <link rel="stylesheet" type="text/css" href="./node_modules/notyf/notyf.min.css&quo ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

Having trouble retrieving values from Promise.allSettled on Node.js 12 using TypeScript version 3.8.3

Currently, I am delving into NodeJs 12 and exploring the Promise.allSettled() function along with its application. The code snippet that I have crafted allows me to display the status in the console, but there seems to be a hitch when attempting to print t ...

Upgrade from Angular 4 to Angular 5 via the Visual Studio template is causing some challenges

I am in the process of upgrading my Angular project from version 4 to version 5, which is included in the template provided by Visual Studio 2017 (File -> New -> Project -> ASP.NET Core Web Application -> Angular). However, all the angular packages defaul ...

How can one effectively import and save data from a CSV file into an array comprised of objects?

I am looking to read a CSV file and store it in a variable for future access, preferably as an array of objects. However, when trying the following code snippet: const csv = fs .createReadStream('data.csv') .pipe(csv.default({ separator: &ap ...

What is the best way to transform RestApi object information into an Array?

How can I transform the data fetched from PokeApi into an Array that can be used in Angular? When trying to assign it to an Array directly in HTML, it gives an error due to its Object return type. getPokemonDetail(index) { return this.http.get(`${this ...

Improving Performance with Reusing Selectors in Ngxs

Working with Angular using the container/presentation pattern and Ngxs presents a challenge for me. The issue I am facing is that I have one container component nested within another container component, both calling the same @Select: @Select(State.example ...

The error message "Property 'hideKeyboardAccessoryBar' does not exist on type 'Keyboard'." appeared while using the IONIC Moodle App

Having an issue in the IONIC Moodle App with a typescript error stating that property 'hideKeyboardAccessoryBar' does not exist on type 'Keyboard'. An ionic error occurred when running CMD, displaying the following error: [14:58:02] ...

Prevent side menu from automatically hiding when clicking on the heading

My menu is set up with headings and subheadings. When I click on the headings, it expands to display the corresponding subheadings, but it automatically collapses when clicking on the headings. I want it to stay expanded when clicking on the headings. He ...