Angular13运行ng serve报Can't bind to 'ngIf'不是div已知属性错误如何解决
Angular 13 ng serve 报错 Can't bind to 'ngIf' 排查方案
执行ng serve启动Angular13项目时VSCode抛出报错:
Can't bind to 'ngIf' since it isn't a known property of 'div'
已验证无效的通用方案
- 项目仅单个根模块,已确认正确引入BrowserModule
- 已核对
*ngIf拼写正确,未出现小写ngif的书写错误
可行解决步骤
- 匹配Angular语言服务插件版本
VSCode内置的Angular Language Service插件版本与项目Angular大版本不匹配是高频触发原因,Angular13对应兼容的插件版本为v13.x分支,打开VSCode插件面板找到Angular Language Service,选择「安装其它版本」,挑选任意13.x版本安装后重启编辑器即可消除误报。 - 校验根模块配置结构
确认BrowserModule是放置在@NgModule的imports数组中,而非declarations、providers等其他数组,根模块参考配置如下:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], bootstrap: [AppComponent] }) export class AppModule { }
- 清除缓存重启服务
本地缓存损坏也会触发该异常,执行以下命令清理缓存后重新启动项目即可:
rm -rf node_modules .angular npm install ng serve
- 独立组件额外配置
如果项目使用的是Angular13支持的独立组件(未在NgModule中声明的组件),需要在组件的@Component装饰器的imports数组中单独引入CommonModule:
import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-root', standalone: true, imports: [CommonModule], template: `<div *ngIf="isVisible">展示内容</div>` }) export class AppComponent { isVisible = true; }
内容的提问来源于stack exchange,提问作者Rahul Pawar
相关产品推荐
相关产品推荐

