Sapper6fd
Sapper6fd

Reputation: 145

Why is this ngif not working properly with a boolean?

I've come across an odd issue when using an ngif statement in my template. The statement is supposed to display render a "Valid" icon when the condition is true. So some reason though it wont render anything at all. I have confirmed the condition is coming through as true as when I output the condition to the console, it shows as true or false depending on the date correctly. Am I doing something wrong here?

detail.component.html

<br> Current Status: <span class="badge badge-success" *ngIf="isActive">Active</span>   

detail.component.ts

let isActive = false;
const validToDate = new Date(this.client.validTo);
if (validToDate.getTime() >= this.currentDate.getTime()) {
  isActive = true;
}
console.log(isActive);

Can anyone see what I'm doing wrong here?

Upvotes: 3

Views: 10342

Answers (3)

gbro3n
gbro3n

Reputation: 6967

or me this wasn't working because I'd missed the inclusion of some declarations under @NgModule in app.module.ts:

When running through https://angular.io/start/start-data

@NgModule({
  declarations: [
    AppComponent,
    TopBarComponent,
    ProductListComponent,
    ProductAlertsComponent,
    ProductDetailsComponent,
    CartComponent,
    ShippingComponent
  ],

Upvotes: 1

Chellappan வ
Chellappan வ

Reputation: 27461

If you declare variable inside function. It will not be available outside that function.Declare variable outside function so that you can access that variable in template

Try this

component.ts

export class AppComponent{ 
    isActive = false;
    constructor(){
        const validToDate = new Date(this.client.validTo);
        if (validToDate.getTime() >= this.currentDate.getTime()) {
          this.isActive = true;
        }
        console.log(this.isActive);
    }
}

component.html

<br> Current Status: <span class="badge badge-success" *ngIf="isActive">Active</span> 

Upvotes: 3

ulmas
ulmas

Reputation: 2253

ngIf works off of a class property. You need to declare the isActive as the component class property:

export class MyComponent {
    isActive = false;        
    doSomething() {
        const validToDate = new Date(this.client.validTo);
        if (validToDate.getTime() >= this.currentDate.getTime()) {
            this.isActive = true;
        }
    }
}

Don't forget the false condition!

Upvotes: 2

Related Questions