Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a boolean value using *ngIf

Tags:

angular

component.ts:

public myFlag: boolean = false;
changeFlag(){
  this.myFlag = true;
}

component.html:

<ng-template *ngIf="newPOST">{{newPOST}}</ng-template>

I expect to see the true when I press the button that calls changeFlag() but in my console is always like this:

<!--bindings={
  "ng-reflect-ng-if": "false"
}-->

This doesn't become true. How can I bind this boolean every time I press the button to change it?

like image 680
Roula Halabi Avatar asked Mar 07 '23 06:03

Roula Halabi


2 Answers

Check this out according to your example: StackBlitz


Here is the same code, posted here in case of something happens again to the StackBlitz.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  myFlag = false;
}
<button (click)="myFlag = !myFlag">Toggle</button>
<div *ngIf="myFlag" style="color:green">Hey I'm true</div>
<div *ngIf="!myFlag" style="color:red">Hey I'm false</div>
p {
  font-family: Lato;
}
like image 162
Yazan Mehrez Avatar answered Mar 21 '23 00:03

Yazan Mehrez


*ngIf does not work with <ng-template> as it is Structural Directives . You can find more details here

As a work around you can use *ngIf else to achieve it

<div *ngIf="!myFlag;else myFlagTrue;">
</div>
<ng-template #myFlagTrue>{{myFlag}}</ng-template>

Here is the working example

like image 38
Saurabh Agrawal Avatar answered Mar 21 '23 00:03

Saurabh Agrawal