Angular 4+:app.component.html中ngIf指令为何不生效?
问题根源:用错了Angular的ngIf指令语法!
嘿,我一眼就看出问题出在哪啦——你把Angular的指令写法和AngularJS的搞混了!
错误点分析:
你写的是 <p ng-if="0==1">,但Angular(非AngularJS)里的结构型指令有两个关键要求:
- 指令名称是驼峰式的
ngIf,不是短横线分隔的ng-if; - 结构型指令需要加**
*前缀**(这是Angular提供的语法糖,简化了<ng-template>的嵌套写法)。
修正后的代码
app.component.html:
<p>This should appear.</p> <p *ngIf="0 == 1">This shouldn't, and now it won't.</p>
如果要用变量控制显示
要是你想用组件里的变量来控制元素显示,这么改就行:
app.component.ts:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { // 定义一个控制显示的变量,默认设为false shouldShowParagraph = false; }
app.component.html:
<p *ngIf="shouldShowParagraph">This will only show when the variable is true!</p>
额外提醒
如果你的项目是自定义模块(不是Angular CLI默认生成的AppModule),别忘了在模块里导入CommonModule(它包含了ngIf、ngFor这些基础指令):
import { CommonModule } from '@angular/common'; @NgModule({ imports: [CommonModule], // ...其他模块配置 }) export class YourCustomModule {}
内容的提问来源于stack exchange,提问作者FrolickingFerret445
相关产品推荐
相关产品推荐

