欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Angular的built-in指令

发布时间:2023/12/19 编程问答 57 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 propertiesthis.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.

总结

以上是生活随笔为你收集整理的Angular的built-in指令的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。