cluis92
cluis92

Reputation: 932

How to render an item based on a Boolean condition (in Angular v10)

I have a method for finding a date in a list of dates

(Typescript)

checkForItem(date: string, historicalDates: string): boolean {
   if (historicalDates.includes(date)){
      return true;
   } else {
      return false;
   }
}

I want to call it in my html in an ngIf condition

(HTML)

<ng-container *ngIf=checkForItem(element.date, element.historicalDates)>
   Confirmed
</ng-container>

I'm not sure if the syntax for the ngIf statement is correct. Basically, what is the syntax to check a condition; I want to call the checkForItem method and if it returns true, I want to show 'Confirmed'

Upvotes: 0

Views: 1667

Answers (1)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9903

You can bind ngIf with boolean expression or function that return boolean value: in both case you need to surround it by quotes "".

So if you want to use function try something like this:

<ng-container *ngIf="checkForItem(element.date, element.historicalDates)">
   Confirmed
</ng-container>

Or you can define bool variable like this:

<ng-container *ngIf="IsShow">
   Confirmed
</ng-container>

And in your component:

checkForItem(date: string, historicalDates: string): void {
    if(historicalDates.includes(date)){
        this.IsShow = true;
    } else {
        this.IsShow = false;
    }
 }

Upvotes: 1

Related Questions