【Angular6+】属性及样式绑定

20次阅读

共计 993 个字符,预计需要花费 3 分钟才能阅读完成。

Angular6_属性及样式绑定
Angular 通过 [] 来绑定数值、变量或者表达式,这种绑定是单向数据绑定。
属性绑定
属性绑定分为两种

Property 元素的常规属性,比如 src、disabled 等
<img [src]=”heroImageUrl” />
<button [disabled]=”isUnchanged”>Cancel is disabled</button>
<div [ngClass]=”classes”>[ngClass] binding to the classes property</div>
<app-hero-detail [hero]=”currentHero”></app-hero-detail>

Attribute
元素的非常规属性,比如 colspan 等
<tr>
<td [attr.colspan]=”1 + 1″>One-Two</td>
</tr>

CSS 类绑定
借助 CSS 类绑定,可以从元素的 class attribute 上添加和移除 CSS 类名。
<!– 这是一个或者全有或者全无的替换型绑定。
即当 badCurly 有值时 class 这个 attribute 设置的内容会被完全覆盖 –>
<div class=”bad curly special” [class]=”badCurly”>Bad curly</div>
<!– toggle the “special” class on/off with a property –>
<div [class.special]=”isSpecial”>The class binding is special</div>
样式绑定
样式绑定的语法与属性绑定类似。但方括号中的部分不是元素的属性名,而由 style 前缀,一个点 (.) 和 CSS 样式的属性名组成。形如:[style.style-property]。
<button [style.color]=”isSpecial ? ‘red’: ‘green'”>Red</button>
<button [style.background-color]=”canSave ? ‘cyan’: ‘grey'”>Save</button>
<button [style.font-size.em]=”isSpecial ? 3 : 1″>Big</button>
<button [style.font-size.%]=”!isSpecial ? 150 : 50″>Small</button>

正文完
 0