angular styles 或 styleUrls 属性 组件样式

在 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 <
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值