angular styles 或 styleUrls 屬性 元件樣式
阿新 • • 發佈:2019-01-29
在 Angular 中,我們可以在設定元件元資料時通過 styles 或 styleUrls 屬性,來設定元件的內聯樣式和外聯樣式。
使用 styles 屬性
import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-simple-form',
template: `
...
`,
styles: [`
:host { margin: 10px; }
input:focus { font-weight: bold;}
` ]
}) export class SimpleFormComponent implements OnInit {
@Input() message: string;
@Output() update = new EventEmitter<{text: string}>();
ngOnInit() {}
}
上面示例中 :host 表示選擇宿主元素,即 AppComponent 元件模板中的 app-simple-form 元素。
用過 AngularJS 1.x 的同學,對 ng-class 應該很熟悉,通過它我們能夠根據條件,為元素動態的新增或移除對應的樣式。在 Angular 中,對應的指令是 ngClass 。接下來我們來看一下,ngClass 指令的具體應用。
使用 ngClass 指令
ngClass 指令接收一個物件字面量,物件的 key 是 CSS class 的名稱,value 的值是 truthy/falsy 的值,表示是否應用該樣式。
@Component({
selector: 'app-simple-form',
template: `
<div>
{{message}}
<input #myInput
type="text"
[(ngModel)]="message"
[ngClass]="{mousedown: isMousedown}"
(mousedown)="isMousedown = true"
(mouseup)="isMousedown = false"
(mouseleave)="isMousedown = false"
>
<button (click)="update.emit({text: message})">更新</button>
</div>
` ,
styles: [`
:host { margin: 10px; }
.mousedown { border: 2px solid green; }
input:focus { font-weight: bold; outline: none;}
` ]
}) export class SimpleFormComponent implements OnInit {
isMousedown: boolean; // ... }
ngClass 指令用法
<!-- 使用布林值 -->
<div [ngClass]="{bordered: false}">This is never bordered</div>
<div [ngClass]="{bordered: true}">This is always bordered</div>
<!-- 使用元件例項的屬性 -->
<div [ngClass]="{bordered: isBordered}"> Using object literal. Border {{ isBordered ? "ON" : "OFF" }} </div>
<!-- 樣式名包含'-' -->
<div[ngClass]="{'bordered-box': false}"> Class names contains dashes must use single quote </div>
<!-- 使用樣式列表 -->
<div class="base" [ngClass]="['blue', 'round']"> This will always have a blue background and round corners </div>
除了 ngClass 指令外,Angular 還為我們提供了 ngStyle 指令。
使用 ngStyle 指令
ngStyle 指令讓我們可以方便得通過 Angular 表示式,設定 DOM 元素的 CSS 屬性。
ngStyle 指令用法
<div [ngStyle]="{color: 'white', 'background-color': 'blue'}"> Uses fixed white text on blue background </div>
需要注意的是, background-color 需要使用單引號,而 color 不需要。這其中的原因是,ng-style 要求的引數是一個 Javascript 物件,color 是一個有效的 key,而 background-color 不是一個有效的 key ,所以需要新增 ''。
對於一些場合,我們也可以直接利用 Angular 屬性繫結的語法,來快速設定元素的樣式。
-
設定元素的背景顏色
<div [style.background-color="'yellow'"]> Use fixed yellow background </div>
-
設定元素的字型大小
<!-- 支援單位: px | em | %--> <div> <span [ngStyle]="{color: 'red'}" [style.font-size.px]="fontSize"> Red Text <