无法绑定到“ngIf”,因为它不是“div”角度 17 的已知属性

问题描述 投票:0回答:1

我正在使用 Angular 版本 17 cli

<div class="row" [class.dark-category-box]="themeService.isDark()" *ngIf="trendingCategories">

我收到此错误:

 Can't bind to 'ngIf' since it isn't a known property of 'div' (used in the 
'CategoriesStyleThreeComponent' component template).
If the 'ngIf' is an Angular control flow directive, please make sure that either the 
'NgIf' directive or the 'CommonModule' is included in the '@Component.imports' of this component.

这是应用程序模块:

    import { HttpClientModule } from '@angular/common/http'; 
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgxScrollTopModule } from 'ngx-scrolltop';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { CommonModule } from '@angular/common';  
import {CategoriesStyleThreeComponent} from './components/common/categories-style-three/categories-style-three.component'

 @NgModule({
 declarations: [],
 imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    NgxScrollTopModule,
    HttpClientModule,
    CommonModule
 ],
 providers: [],
 bootstrap: [],
     exports: [CategoriesStyleThreeComponent]
 })
   export class AppModule { }

和我的组件代码:

 import { Component, OnInit } from '@angular/core';
 import { ThemeCustomizerService } from '../theme-customizer/theme-customizer.service';
 import { RouterLink } from '@angular/router';
 import { CategoryService } from '../../../services/category.service';
 import { Category } from '../../../models/category.model';


@Component({
selector: 'app-categories-style-three',
standalone: true,
imports: [RouterLink],
templateUrl: './categories-style-three.component.html',
styleUrls: ['./categories-style-three.component.scss']
})
export class CategoriesStyleThreeComponent implements OnInit {
trendingCategories: Category[];
numCategories: number = 5;

isToggled = false;

constructor(public themeService: ThemeCustomizerService,
    private categoryService: CategoryService) {
    this.themeService.isToggled$.subscribe(isToggled => {
        this.isToggled = isToggled;
    });
}

toggleTheme() {
    this.themeService.toggleTheme();
}

ngOnInit(): void { 
    this.loadTrendingCategories();
}

loadTrendingCategories(): void {
    this.categoryService.getTrendingCategories()
        .subscribe(categories => {
            this.trendingCategories = categories;
            console.log(categories);
        });
  }

 }
 
angular angular17 angular-standalone-components
1个回答
1
投票

如果

CategoriesStyleThreeComponent
是独立的,则确保已将
CommonModule
添加到导入数组!

CommonModule
包含要在 HTML 中使用的
ngClass
ngIf
等指令,您也可以单独导入这些单独的项目。

独立组件需要在组件上添加导入,因为它们可以作为单独的单元运行,而不依赖于模块!

...
@Component({
  ...
  standalone: true,
  imports: [
    ...
    CommonModule,
    ...
  ],
  ...
})
export class CategoriesStyleThreeComponent {
    ...
© www.soinside.com 2019 - 2024. All rights reserved.