Angular的built-in指令

简介: Angular的built-in指令

Angular built-in指令分为attribute指令和structural指令两种。


Attribute指令

最常用的attribute指令有NgClass, NgStyle和NgModel三种。


NgClass

动态添加或者删除html标签的css类。


例子:

<!-- toggle the "special" class on/off with a property -->
<div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>

isSpecial为true时,div标签打上special的css类。

一个更复杂一些的例子:

<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>

div的class绑定到了Component的property,名为currentClasses.

在Component的实现代码里,currentclasses的赋值逻辑:

currentClasses: {};
/* . . . */
  setCurrentClasses() {
    // CSS classes: added/removed per current state of component properties
    this.currentClasses =  {
      saveable: this.canSave,
      modified: !this.isUnchanged,
      special:  this.isSpecial
    };
  }

NgModel

例子:

<label for="example-ngModel">[(ngModel)]:</label>
<input [(ngModel)]="currentItem.name" id="example-ngModel">

上面实际上是一个双向绑定的语法糖,等价于:

<label for="without">without NgModel:</label>
<input [value]="currentItem.name" (input)="currentItem.name=$event.target.value" id="without">

Structural指令

ngIf

例子:

<div *ngIf="hero" class="name">{{hero.name}}</div>

实际是个语法糖,等价于:

<ng-template [ngIf]="hero">
  <div class="name">{{hero.name}}</div>
</ng-template>

ngFor

例子:

<app-item-detail *ngFor="let item of items" [item]="item"></app-item-detail>

let item of items的含义:Take each item in the items array, store it in the local item looping variable, and make it available to the templated HTML for each iteration.


ngFor指令有一个内置属性index:

<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>


上面的例子,将index属性赋给template变量i.

相关文章
|
5天前
|
JavaScript
如何在 Angular 中使用 ViewChild 来访问子组件、指令或 DOM 元素
如何在 Angular 中使用 ViewChild 来访问子组件、指令或 DOM 元素
4 0
|
5天前
|
索引
Angular 中的 ngFor 指令
Angular 中的 ngFor 指令
8 0
|
5天前
|
JavaScript
如何在自定义 Angular 指令中使用 @HostBinding 和 @HostListener
如何在自定义 Angular 指令中使用 @HostBinding 和 @HostListener
8 0
|
3月前
|
JavaScript 前端开发 编译器
Angular 中的结构指令运行时的工作原理
Angular 中的结构指令运行时的工作原理
|
前端开发 JavaScript
对于Angular表达式以及重要指令的研究心得【前端实战Angular框架】
对于Angular表达式以及重要指令的研究心得【前端实战Angular框架】
对于Angular表达式以及重要指令的研究心得【前端实战Angular框架】
angular32-其他指令ng-checked
angular32-其他指令ng-checked
67 0
angular32-其他指令ng-checked
angular21-关于指令标准属性
angular21-关于指令标准属性
72 0
angular21-关于指令标准属性