typescript ngIf不工作,即使我使用 *ngIf=“true”,它也不会显示,*ngIf=“false”也不会显示,

ni65a41a  于 2023-05-23  发布在  TypeScript
关注(0)|答案(1)|浏览(243)

如果某个变量是null,我想隐藏一个div,但是即使我直接赋值true,*ngIf也不起作用。
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>
...

控制台出错:

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

psyklopzlink上的解决方案
我已经将TreeComponent导入app.module.ts@NgModuledeclarations

ig9co6j1

ig9co6j11#

ngIf需要Angular的CommonModule

CommonModule安装到组件的父模块中,因为它具有ngIf指令。我在你的例子中没有看到这一点。

import {CommonModule} from '@angular/common';

@NgModule({
    imports: [CommonModule]
})

相关问题