Changing value of mat-option based off a conditonal in *ngIf

271 Views Asked by At

I have two options for values when it comes to my mat-option

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

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

I want to set a conditional in my html based off of two variables I have:
public SentDate;
public CurrentDate;

I'm getting these values from a datepicker. My desired result is, if the dates are the same, display tempTime in mat-options if not display temptimesHighNumber

Here is what I've tried:

<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>

Here is the error I'm getting: Can't have multiple template bindings on one element. Use only one attribute prefixed with * ("heckConditionSentDate === checkConditionCurrentDate" What is the proper way to use *ngIf or am I approaching this the wrong way?

1

There are 1 best solutions below

0
On

You can wrap each mat-option with ng-container and put *ngIf on ngContainer like this :

    <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>