Angular的built-in指令
Angular built-in指令分為attribute指令和structural指令兩種。
Attribute指令
最常用的attribute指令有NgClass, NgStyle和NgModel三種。
NgClass
動(dòng)態(tài)添加或者刪除html標(biāo)簽的css類(lèi)。
例子:
<!-- toggle the "special" class on/off with a property --> <div [ngClass]="isSpecial ? 'special' : ''">This div is special</div>isSpecial為true時(shí),div標(biāo)簽打上special的css類(lèi)。
一個(gè)更復(fù)雜一些的例子:
<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div>div的class綁定到了Component的property,名為currentClasses.
在Component的實(shí)現(xiàn)代碼里,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">上面實(shí)際上是一個(gè)雙向綁定的語(yǔ)法糖,等價(jià)于:
<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>實(shí)際是個(gè)語(yǔ)法糖,等價(jià)于:
<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指令有一個(gè)內(nèi)置屬性index:
<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>上面的例子,將index屬性賦給template變量i.
總結(jié)
以上是生活随笔為你收集整理的Angular的built-in指令的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 第四范式发布式说大模型 戴文渊:大模型未
- 下一篇: Angular [(ngModel)]的