htmlangulartypescriptangular-directiveangular-ng-if

ngIf not working. Even if I do *ngIf="true" it doesn't show, neither does *ngIf="false"


I want hide a div if some variable is null, but *ngIf is not working even if I assign true directly.

tree.component.ts

import { Component, OnInit } from '@angular/core';
import { Tree} from '../model/tree';
import { TreeService } from '../service/tree.service';

@Component({
  selector: 'app-tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.css']
})
export class TreeComponent implements OnInit {

  canShow: boolean = true;
  tree!: Tree;

  constructor(private treeService:TreeService) {
  }

  ngOnInit(): void {
    this.tree= this.treeService.returnTree();
  }

}

tree.component.html

...

          <div *ngIf="canShow">
            <h1 class="sm:text-2xl font-medium mb-2 text-gray-900">Significado dos nomes populares</h1>
            <p class="pb-3 leading-relaxed text-gray-500">{{tree.nameMeaning}}</p>
          </div>
...

tree.component.html

...

          <div *ngIf="true">
            <h1 class="sm:text-2xl font-medium mb-2 text-gray-900">Significado dos nomes populares</h1>
            <p class="pb-3 leading-relaxed text-gray-500">{{tree.nameMeaning}}</p>
          </div>
...

Error in console:

NG0303: Can't bind to 'ngIf' since it isn't a known property of 'h2'.

Solution by psyklopz at link

I've imported TreeComponent into @NgModule declarations of app.module.ts.


Solution

  • ngIf requires the CommonModule in Angular

    Install the CommonModule into the parent module of your component, as it has the ngIf directive. I did not see that imported in your example.

    import {CommonModule} from '@angular/common';
    
    @NgModule({
        imports: [CommonModule]
    })