Angular语法(三)——数据绑定


绑定类型

绑定类型可以按照数据流的方向分为三类:从源到视图,从视图到源,以及双向序列
1

示例

<!-- Bind button disabled state to `isUnchanged` property --> <button [disabled]="isUnchanged">Save</button>

绑定对象

1

Property binding

<img [src]="heroImageUrl"> <img bind-src="heroImageUrl"> <div [ngClass]="classes">[ngClass] binding to the classes property</div>

不要忘记方括号

正确的写法

<app-hero-detail [hero]="currentHero"></app-hero-detail>

错误的写法

<!-- ERROR: HeroDetailComponent.hero expects a  Hero object, not the string "currentHero" --> <app-hero-detail hero="currentHero"></app-hero-detail>

HeroDetail组件的hero属性需要一个Hero对象,这正是您在属性绑定中发送的内容:括号告诉Angular评估模板表达式。
如果省略方括号,Angular会将该字符串视为常量并使用该字符串初始化目标属性。

属性绑定还是插值?

下面写法等效

<p><img src="{{heroImageUrl}}"> is the <i>interpolated</i> image.</p> <p><img [src]="heroImageUrl"> is the <i>property bound</i> image.</p> <p><span>"{{title}}" is the <i>interpolated</i> title.</span></p> <p>"<span [innerHTML]="title"></span>" is the <i>property bound</i> title.</p>

Attribute, class, and style bindings

Attribute binding

错误的写法

<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>

报错

Template parse errors:
Can't bind to 'colspan' since it isn't a known native property

正确的写法

<!-- expression calculates colspan=2 --> <tr><td [attr.colspan]="1 + 1">One-Two</td></tr>

Class binding

不使用bind

<div class="bad curly special">Bad curly special</div>

使用bind

<!-- reset/override all class names with a binding --> <div class="bad curly special" [class]="badCurly">Bad curly</div>

Style binding

Style binding语法类似于Property binding。 代替括号内的元素属性,从前缀样式开始,后跟一个点(.)和一个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>

Event binding

两种写法

<button (click)="onSave()">Save</button> <button on-click="onSave()">On Save</button>
<input [value]="currentHero.name" (input)="currentHero.name=$event.target.value" >

还可以自定义Event

Two-way binding ( [(...)] )

Angular为双向绑定提供了一种特殊的双向数据绑定语法,[(x)]。 [(x)]语法将属性绑定的括号[x]与事件绑定的括号(x)组合在一起。

[( )] = BANANA IN A BOX
香蕉在一个盒子里
在盒子中形象化一个香蕉,记住圆括号在括号内。

示例

<app-sizer [(size)]="fontSizePx"></app-sizer>
<div [style.font-size.px]="fontSizePx">Resizable Text</div>

双向绑定语法实际上只是语法绑定和事件绑定的语法糖。

<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM