在 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 <