ngIf 是 Angular 的行为指令。
基本写法:<div *ngIf="hero" class="name">{{ hero.name }} </div>
当 ngIf 表达式求值为 truthy 时,Angular会渲染在then子句中提供的模板;当为falsy 时,Angular会渲染在可选的else子句中提供的模板。
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>Content to render when condition is true.</ng-template>
<ng-template #elseBlock>Content to render when condition is false.</ng-template>
以下是JavaScript 中为 falsy 的值, 其余为 truthy:

用法举例:
app.components.ts:
export class AppComponent {
pokemonName: string = '';
constructor() {}
handleChange(event: any) {
this.pokemonName = event.target.value;
}
}
app.component.html:
<input> 元素使用了属性绑定和事件绑定。
属性绑定语法:[],属性绑定是单向数据流,将数据放到web页面上。
事件绑定语法:(),事件向上传递,数据向下流动。
<input type="text" [value]="pokemonName" (input)="handleChange($event)" />
<p>{{ pokemonName }}</p>
<!-- 1. basic usage -->
<!-- <div *ngIf="!pokemonName">No search results found...</div> -->
<!-- 2.more robust version then above -->
<ng-container *ngIf="pokemonName.length; then pokemonList; else noPokemon">
</ng-container>
<ng-template #pokemonList>
<h1>All pokemon available</h1>
...
</ng-template>
<ng-template #noPokemon>
<h1>No pokemon available</h1>
</ng-template>
初始界面:

input 任意输入:

本文详细解释了Angular中的ngIf行为指令,包括其工作原理、基本语法以及如何根据条件动态渲染或隐藏元素。同时介绍了与之相关的双向数据绑定和模板使用示例。

392

被折叠的 条评论
为什么被折叠?



