angular 指令

发布于 2021-04-06  737 次阅读


angular 指令

angular 提供了 两种内置指令:属性型,结构型指令。

属性型指令:监听并修改其他HTML元素和组件的行为,Attribute,Property。因为类似HTML的属性,因此得名。
结构型指令:用于设置改变HTML布局。塑造或者重塑DOM结构,比如添加、移除或维护这些元素。

属性型指令

常见的属性型指令有:NgClass, NgStyle,NgModel

NgClass可以同时添加或者删除好几个 css 类。

<div [ngClass]="isSpecial?'special':''">This div is specail.</div>

可以将一个组件属性来设置 css 类

currentClasses:{}

setCurrentClasses(){
    this.currentClasses={
        saveable:this.cansave,
        modified:!this.isUnChange,
        special:this.isSpecial
    };
}
<div [ngClass]="currentClasses">This div is initially saveable,unchanged,and speical.</div>

NgStyle根据组件的状态同时设置多个内联样式。有些情况使用样式绑定来设置单个样式值。

currentStyles:{}

setCurrentStyles(){
    this.currentStyles = {
        'font-style':this.canSave?'italic':'normal',
        'font-eight':this.isUnchanged?'bold':'normal'
    };
}
<div [ngStyle]="currentStyles">This</div>

NgModel进行数据的双向绑定,仅适用通过ControlValueAccessor适配过这种协议的元素。

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

自定义属性指令

import {Directive,ElementRef,HostListener} from '@angular/core';

@Directive({
    selector:"[appHighlight]"
})
export class HightLightDirective{
    @Input('appHighlight') highlightColor:string;
    @Input() defaultColor:string;

    constuctor(el:ElementRef){
    }

    @HostListener('mouseenter') onMouseEnter(){
        this.highlight(this.highlightColor||this.defaultColor||'yellow');
    }

    @HostListener('mouseleave') onMouseLeave(){
        this.highlight(null);
    }

    private highlight(color:string){
        this.el.nativeElement.style.backgroundColor = color;
    }
}
}
<p [appHighlight]="color" defaultColor="violte">
    Highlight
</p>

可以依次添加多个属性。

结构型指令

NgIf指令用于在宿主元素上来从DOM中添加或删除元素。NgIf会从DOM中删除元素并销毁其所有的子组件。

可以通过样式来控制元素的显隐,此时不会销毁元素及其子组件。

NgFor是一个重复器指令,是一种用来显示条目列表的方法。

trackByNgFor一起使用可以优化表的更新。

trackByItems(index:number,item:item):number{return item.id;}
<div *ngFor="let item of items;trackBy:trackByItems">
    {{item.id}} {{item.name}}
</div>

不理解,猜测是此时不会重新创建未修改的元素

自定义结构指令

*是一个用来简化复杂语法的语法糖。
angular将*ngIf翻译为<ng-template>元素。

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

NgSwitch

NgSwitch根据条件显示几个可能的元素中的一个,只会将选中的元素放入DOM。

<div [ngSwitch]="condition">
    <app-stout-item *ngSwitchCase="'stout'" [item]="currentItem"></app-stout-item>
    <app-stout-item *ngSwitchDefault="'stout'" [item]="currentItem"></app-stout-item>
</div>

NgSwitch是属性指令,ngSwitchCase以及ngSwitchDefault是结构型指令。

ngNonBindable

ngNonBindable伪指令,可以让Angular不对模板中的表达式进行求值。


朝闻道,夕死可矣