常用指令

在 Angular 中最常用的指令分为两种,它们分别是 属性型指令结构型指令

NgClass#

  • 作用:添加或移除一组 CSS 类

NgStyle#

  • 作用:添加或移除一组 CSS 样式

NgModel#

  • 作用:双向绑定到 HTML 表单元素

NgIf#

  • 作用:根据条件添加或移除 DOM

  • 语法:

<div class="box" *ngIf="false">看不见我</div>

我们也可以通过类绑定样式绑定来显示或隐藏一个元素。

<!-- isSpecial is true -->
<div [class.hidden]="!isSpecial">Show with class</div>
<div [class.hidden]="isSpecial">Hide with class</div>

<div [style.display]="isSpecial ? 'block' : 'none'">Show with style</div>
<div [style.display]="isSpecial ? 'none'  : 'block'">Hide with style</div>

NgSwitch#

  • 作用:类似于 JavaScript 中的 switch 语句,根据条件渲染多个选项中的一个。

  • 语法:该指令包括三个相互协作的指令:NgSwitchNgSwitchCaseNgSwitchDefault

<div [ngSwitch]="currentHero.emotion">
  <app-happy-hero    *ngSwitchCase="'happy'"    [hero]="currentHero"></app-happy-hero>
  <app-sad-hero      *ngSwitchCase="'sad'"      [hero]="currentHero"></app-sad-hero>
  <app-confused-hero *ngSwitchCase="'confused'" [hero]="currentHero"></app-confused-hero>
  <app-unknown-hero  *ngSwitchDefault           [hero]="currentHero"></app-unknown-hero>
</div>

NgFor#

  • 作用:列表渲染

  • 语法:

<div *ngFor="let hero of heroes">{{hero.name}}</div>

带索引的 `*ngFor`#

<ul>
  <li *ngFor="let item of todos; let i = index">{{ item.title + i }}</li>
</ul>

自定义指令#

参考文档:

posted @   1640808365  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-03-19 数据库读写分离之配置Django实现数据库读写分离
点击右上角即可分享
微信分享提示
主题色彩