angularangular-ng-if

angular *ngIf not working when ngstyle works


This is my angular code when bottom element load working ngif is not working, why could be so? Below there is component code and html , which are using in my snippet. Problem is really strange, because code should work. But !loading expression works well for ngif.
Before loading;

enter image description here
After loading;

enter image description here

export class AppComponent implements OnInit {
  title = 'Anular Application';
  //products: Iproduct[] = data;
  products: Iproduct[] = [];
  parentData: string = "This is parent data";
  details: boolean = false;
  loading: boolean = false;
  variable: boolean = true;
  constructor(private productsService: ProductsService,   ) {
  }

  //service proving us the data
  ngOnInit(): void {
    this.loading = true
    this.productsService.getProducts().subscribe(products => {
      setTimeout(() => {}, 2000);
      this.products = products;
      this.loading = false;
      this.variable = false;
    });

  }
}
<h1 class="text-center" [ngStyle]="{'visibility': loading ? 'visible' : 'hidden' }">Loading ngstyle 23..</h1>
<h1  *ngIf="loading" class="text-center">Loading if ..</h1>
<h1  *ngIf="!loading" class="text-center">not Loading if ..</h1>
<app-product-component [stringHardCode]="'string hardcoded'" [childData]="parentData" 
    *ngFor="let product of products; let i = index" [product]="product">


Solution

  • <h1 class="text-center" [ngStyle]="{'visibility': loading ? 'visible' : 'hidden' }">Loading using ngStyle..</h1>
    <h1 *ngIf="loading" class="text-center">Loading using *ngIf..</h1>
    <h1 *ngIf="!loading" class="text-center">Not Loading using *ngIf..</h1>
    <app-product-component
      [stringHardCode]="'string hardcoded'"
      [childData]="parentData"
      *ngFor="let product of products; let i = index"
      [product]="product">
    </app-product-component>
    
     **.ts file**
    export class AppComponent implements OnInit {
      title = 'Angular Application';
      products: IProduct[] = [];
      parentData: string = "This is parent data";
      loading: boolean = true;
      variable: boolean = true;
    
      constructor(private productsService: ProductsService) {}
    
      ngOnInit(): void {
        this.productsService.getProducts().subscribe(products => {
          setTimeout(() => {
            this.products = products;
            this.loading = false; 
            this.variable = false;
          }, 2000);
        });
      }
    }
    

    With these changes, the loading and conditional rendering should work as expected.