1

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.

Ruli
  • 2,592
  • 12
  • 30
  • 40
hil-beer-t
  • 11
  • 3
  • 2
    Check the parent elements, maybe you have another `ngIf` that prevents this markup to be rendered. – Octavian Mărculescu Apr 06 '22 at 19:53
  • 1
    2 likely causes. 1) You have a fatal exception somewhere, view the console output in your browser to see if there are Exceptions being thrown. 2) You are looking at the wrong rendered component or output. Add something temporary but identifying to it to verify what it is you are seeing. – Igor Apr 06 '22 at 19:57
  • It seems to be working now. Error in console: `NG0303: Can't bind to 'ngIf' since it isn't a known property of 'h2'.` Solution: [link](https://stackoverflow.com/questions/39058075/cant-bind-to-ngif-since-it-isnt-a-known-property-of-div). I've imported `TreeComponent` into `@NgModule` of `app.module.ts`. – hil-beer-t Apr 06 '22 at 20:18

1 Answers1

0

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]
})
Stokely
  • 12,444
  • 2
  • 35
  • 23