您的位置:首页 > Web前端 > AngularJS

Angular学习笔记(二)之Angular的内置指令

2017-12-28 14:14 232 查看
内置指令是已经导入过的,可以在组件中直接使用

ngIf

语法:
<div *ngIf="condition">...</div>
,condition为true时显示,false时不显示

<div *ngIf="false">first</div>       <!--不显示-->
<div *ngIf="a>b">second</div>        <!--a 的值大于b 时显示-->
<div *ngIf="str=='yes'">third</div>  <!--str 的值为 yes 时显示-->
<div *ngIf="myFunc()">fouth</div>    <!--函数返回结果为 true 时显示-->


ngFor

语法:
<div *ngFor="let item of items; let i = index"></div>
,items是来自组件控制器的一组项的集合,item是用来接收items中的每个元素的变量,i 用来接收索引值。

ts

this.people=[
{name:'张三',age:'35',city:'北京'},
{name:'李四',age:'25',city:'上海'},
{name:'赵五',age:'28',city:'广州'},
]


html

<table>
<tr>
<th>序号</th>
<th>名字</th>
<th>年龄</th>
<th>城市</th>
</tr>
<tr *ngFor="let p of people; let x = index">
<td>{{x+1}}</td>
<td>{{p.name}}</td>
<td>{{p.age}}</td>
<td>{{p.city}}</td>
</tr>
</table>


执行结果

序号 名字 年龄 城市

1 张三 35 北京

2 李四 25 上海

3 赵五 28 广州

ngSwitch

根据一个给定的条件渲染不同的元素。

格式 : [ngSwitch] 先与目标进行绑定,ngSwitchCase 列出每个可能性

<div class="container" [ngSwitch]="myVar">
<div *ngSwitchCase="'A'">Var is A</div>
<div *ngSwitchCase="'B'">Var is B</div>
<div *ngSwitchDefault>Var is something else</div>
</div>


myVar的值为A时,显示Var is A,

myVar的值为B时,显示Var is B,

myVar的值既不属于A,也不属于B时,显示Var is something else

ngSwitchDefault元素可选,默认情况下若没有匹配到期望值,是不会渲染任何东西的

ngStyle

给特定的DOM元素设定CSS属性

语法一(常用于单个样式属性)

[style.<cssproperty>]="value"


语法二(常用于多个样式属性)

[ngStyle]="{<cssproperty>:value,<cssproperty>:value}"


<div [style.background-color]="'yellow'">这里显示背景为黄色</div>

<div [style.font-size.px]="'12'">这里的文字大小为12px。后缀.px表明我们设置font-size属性值以像素为单位</div>

<div [style.font-size.px]="fontSize">这里的文字大小为ts中设置的变量fontSize的值</div>

<div [ngStyle]="{'background-color':'blue',color:'white'}">这里显示蓝色背景白色字体</div>

<div [ngStyle]="{'background-color':'blue','font-size':fontSize+'px'}">这里显示蓝色背景,字体大小为ts中设置的变量fontSize的值</div>


Tips :

[style.background-color]="'yellow'"
,注意yellow带单引号,表示明确的字符串值,如果
[style.background-color]="yellow"
,yellow不带单引号,则表示名为yellow的变量

[ngStyle]="{'background-color':'blue',color:'white'}"
中的background-color属性带有引号,是因为连字符不允许出现在对象的键名当中的,除非它是一个字符串。

ngClass

动态设置和改变一个给定DOM元素的CSS类

语法一:传入一个对象字面量,该对象以类名作为键,值是一个用来表明该类的true/false值。
[ngClass]="object"


语法二:传入一个数组型字面量,数组型写明那些类名会被添加到元素上。

css:

.bordered{
border:1px dashed black;
background-color: #eee;
}


html:

<div [ngClass]="{bordered:true}">类bordered生效</div>

<div [ngClass]="{bordered:isBordered}">ts中变量isBordered值为true时,类bordered生效</div>

<div [ngClass]="classObj">在ts中声明classObj对象,如classesObj = {bordered:true};</div>

<div class="base" [ngClass]="['blue','round']">这里使用base类、blue类和round类,也使用.base.blue.round类样式</div>


补充:另一种写法

[class.active] = "currentId == menu.id"
//表达式 "currentId == menu.id" 返回值为true时激活active类


ngNonBindable

不要编译或者绑定页面中的某个特殊部分,比如{{content}},不想使用{{ }}模版语法,只想纯文本渲染。

html

<div>
<span class="bordered">{{content}}</span>
<span class="pre" ngNonBindable>This is waht {{content}} rendered</span>
</div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: