Angular - Attribute Directive (屬性型指令)

  • 2008
  • 0
  • 2018-05-11

這種指令會修改元素的外觀或者是行為,

常用的有三種,ngModel、NgStyle、NgClass

Attribute Directive (屬性型指令)

特性:本身不會有Template ,Angular 內建的Attribute Directive 有三種(ngModel、ngClass、ngStyle)

首先介紹 : ngStyle

範例情境說明:設計一個Button去增加一個Counter的值,再透過Counter值的改變動態的去改變一段文字的大小(font-size),

component.ts這邊很簡單,定義一個property:Counter跟累加的Function

h3_counter = 0;

AddH3Counter() {
    this.h3_counter++;
  }

template:

<div>
    <h3 [ngStyle]="{'font-size': (12+h3_counter)+'px'}">測試 ngStyle Attriute Directive 用的文字,目前點擊次數:{{h3_counter}}</h3>
    <button (click)="AddH3Counter()">Click Button</button>
</div>

h3是透過property binding 到一個ngStyle ,但是 ngStyle 並不是h3 的property 也不是他的Attribute

ngStyle本身是一個Attribute  Directive,這個directive透過中括號去繫結後面的物件,

這個物件的屬性裡面就是定義要套用的css style

設定font-size的時候結尾要記得給單位

 

也可以不要在template內定義,改為方法回傳,從component裡面去回傳一個物件到前端

在component 內新增一個function

GetH3Style() {
    return { 'font-size': 12 + this.h3_counter + 'px' };
  }

template 改為

<div>
    <h3 [ngStyle]="GetH3Style()">測試 ngStyle Attriute Directive 用的文字,目前點擊次數:{{h3_counter}}</h3>
    <button (click)="AddH3Counter()">Click Button</button>
</div>

效果是一樣的!

 

或是使用更簡潔的語法來套用樣式

<h3 [style.font-size]="12 + this.h3_counter + 'px'" [style.color]="'blue'">測試 ngStyle Attriute Directive 更簡潔的用法</h3>

不用ngStyle,而是直接使用[style.屬性]

記得 有些屬性是接受Javascript的物件 , 例如 style.color 的設定值是接受一個字串,

在寫的時候就要給單引號,否則會出錯

 

ngClass

用法跟ngStyle非常像,一樣有兩種寫法(基本寫法以及簡化寫法)

component.ts 一樣設計一個累加變數的機制

h4_counter = 0;

AddH4Counter() {
    this.h4_counter++;
  }

在設計一個class

.HL {
    background-color: red;
}

template:

<div>
    <h4 [ngClass]="{HL: h4_counter%2==0}">測試ngClass 使用的文字 {{h4_counter}}</h4>

    <h4 [class.HL]="h4_counter%2 == 0">測試ngClass 使用的文字 {{h4_counter}} 簡化的寫法</h4>

    <button (click)="AddH4Counter()">H4 Button</button>
</div>

由template可以看到兩種ngClass的用法

第一種是標準的寫法,[ngClass] 後面是接一個物件,物件內部 className:boolean

其中boolean 也可以透過component定義的Function 回傳boolean過來

第二種用法是簡化的寫法,用法跟上面的ngStyle類似,只是這邊接收的值是boolean