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

Ensure to wait for the user ID before accessing Firestore collections

Trying to wrap my head around rxJs and experimenting with using the where query in Firestore collection. However, I've run into an issue where the output of this collection is dependent on retrieving the user ID from Firebase Auth. Here's what I ...

Trouble arises in AWS Code Pipeline as a roadblock is encountered with the Module

After many successful builds of my Angular project, it suddenly fails to build on AWS Code Build. I reverted back to a commit before any recent changes, but the error persists. When I run ng build --prod locally, it works fine. However, during the pipeline ...

Obtaining a JSON file from Firebase Storage

Is it possible to retrieve a JSON file from Firebase Storage for use without needing to push it back? If so, how can I accomplish this using Angular with Firebase Storage? If not, would the Firebase database be a better option for this scenario? I have ...

Struggling to access the html elements within a component once the ng2 page has finished loading?

I am working on a web app that utilizes ng2-smart-table and I want to hide all cells within the table. However, when attempting to retrieve all the cells using document.getElementsByTagName("td") in the ngAfterViewInit() lifecycle hook, I noticed that the ...

What steps should I take to resolve the 'invalid mime type' issue while transmitting an image as a binary string to Stability AI via Express?

Currently, I am facing an issue while attempting to utilize the image-to-image API provided by stabilityAI. The task at hand involves sending an image as a binary string through my express server to the stability AI API. However, when I make the POST reque ...

How can the life cycle of a component be maintained after the constructor until the function in the constructor has finished executing?

I'm currently developing an Angular 2 application. Within this application, I have a component responsible for displaying the menu. This component contains an array of menu items that are initially set to be displayed based on permissions retrieved f ...

Managing multiple Sequelize DB connections in NestJS: A guide

I recently came across the example in the NestJS documentation regarding setting up a Sequelize DB connection. I'm curious about how to connect to multiple databases using Sequelize and TypeScript with NestJS. Can anyone provide guidance on this? ...

Allow for an optional second parameter in Typescript type definition

Here are two very similar types that I have: import { VariantProps } from "@stitches/core"; export type VariantOption< Component extends { [key: symbol | string]: any }, VariantName extends keyof VariantProps<Component> > = Extra ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

Is it possible to include parameters in an HTML GET request with Electron.Net?

I have successfully implemented a function in an Angular component within an Electron application using HttpClient: var auth = "Bearer" + "abdedede"; let header = new HttpHeaders({ "Content-Type": 'application/json&a ...

Angular service: Issue with updating value in observable property

Attempting to establish communication between two browser tabs/windows using the BroadcastChannel API. The communication appears to work between two instances of an angular service, but changes to the observable values are not reflected. I am attempting to ...

How can I retrieve the ngx-Summernote runtime value?

I am currently integrating ngx-Summernote into my Ionic 5 + Angular project. Is there a way to access the value using ngModel? I attempted: <div [ngxSummernote]="config" [ngxSummernoteView]="content"></div> The issue I&apo ...

The service subscription in the ngOnInit lifecycle hook is only invoked once and does not remain populated when the route changes

I need some clarification. The Angular app I'm working on is successfully populating data to the view, but when navigating from one component to another, the ngOnInit lifecycle hook doesn't seem to be invoked, leaving the list on the view empty. ...

Troubleshooting an issue with a Typescript React component that is generating an error when using

I am in the process of implementing unit testing in a Typescript and React application. To start off, I have created a very basic component for simplicity's sake. import React from "react"; import ReactDOM from "react-dom"; type T ...

Managing status in Angular applications

I am currently working on a project using Angular 7 and I have the following code snippet: public deleteId(pId){ return this.http.delete<any>(this.deleteUrl(pId), {observe: 'response'}) .pipe(catchError(this.handleError)); } I ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

Angular subscription and observable continuously fetch information

I'm encountering an issue with utilizing subscriptions and observables Here is my code This is my inventory.service.ts getInventoryList = (page: string, pageSize,size) => { const userLocation = this.authService.getUserLocation(); let que ...

A guide on distinguishing between two dates in Ionic3 using either date-fns or Moment libraries

How can I calculate the difference between two dates to determine the end of an employee's service? Similar Question: What is the best way to find the day difference between two dates using Ionic 3? I am looking for a solution on how to get the exac ...

Having trouble with React state not updating?

Hello, I am a beginner in the world of React and currently working on fetching an array of endpoints. My goal is to update the API's status every 15 seconds. Here is the code snippet for the array of endpoints: export const endpoints: string[] = [ " ...

Angular 2 - The constructor of a class cannot be called without using 'new' keyword

Currently, I am working on integrating the angular2-odata library into my project. This is the code snippet I have: @Injectable() class MyODataConfig extends ODataConfiguration { baseUrl = "http://localhost:54872/odata/"; } bootst ...