angular4笔记系列之内置指令

本文深入探讨了Angular中的内置指令,包括属性型指令如NgClass、NgStyle和NgModel,以及结构型指令如NgIf、NgFor和NgSwitch。通过实例展示了如何使用这些指令来动态地修改HTML元素的样式和行为,以及如何控制DOM结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

内置指令

内置属性型指令

属性型指令会监听和修改其它HTML元素或组件的行为、元素属性(Attribute)、DOM属性(Property)。

NgClass

形式:[ngClass]="statement"
通过绑定到NgClass,可以同时添加或移除多个类。

setCurrentClasses() {
  this.currentClasses =  {
    'saveable': this.canSave,
    'modified': !this.isUnchanged,
    'special':  this.isSpecial
  };
}

<div [ngClass]="currentClasses">This div</div>
NgStyle

形式:[ngStyle]="statement"
NgStyle绑定可以同时设置多个内联样式。

setCurrentStyles() {
  this.currentStyles = {
    'font-style':  this.canSave      ? 'italic' : 'normal',
    'font-weight': !this.isUnchanged ? 'bold'   : 'normal',
    'font-size':   this.isSpecial    ? '24px'   : '12px'
  };
}

<div [ngStyle]="currentStyles">This div</div>
NgModel

形式:[(ngModel)]="statement"
使用[(ngModel)]双向绑定到表单元素。

<input [(ngModel)]="currentHero.name">
使用 ngModel 时需要 FormsModule
内置结构型指令
NgIf

形式:*ngIf="statement"

<app-hero-detail *ngIf="isActive"></app-hero-detail>
NgFor

形式:*ngFor="statement"

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

形式:[ngSwitch]="statement"

<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-unknown-hero *ngSwitchDefault [hero]="currentHero"></app-unknown-hero>
</div>
NgSwitch实际上包括三个相互协作的指令:NgSwitch、NgSwitchCase 和 NgSwitchDefault

模板引用变量 ( #var )

模板引用变量通常用来引用模板中的某个DOM元素,它还可以引用Angular组件或指令或Web Component。

<input #phone placeholder="phone number">

<button (click)="callPhone(phone.value)">Call</button>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值