Angular指令

Angular提供了若干内置指令,下面来看看它的神奇:

ngIf

如果要实现一个元素的显示与隐藏,ngIf指令的表达式将会实现这个功能:

<div *ngIf="b">我是一个盒子</div>  //这里的b最终的结果是一个boolean值,b可以是表达式、函数、判断语句等等
ngSwitch

在需要根据不同的条件来渲染不同的元素时,此时用ngIf会感觉特别的繁琐,ngSwitch解决了这一问题:

<div [ngSwitch]="myBook">    //myBook是一个字符串变量   J、Q、K是变量的随机值,*ngSwitchDefault是默认值
  <div *ngSwitchCase="'J'">book is J</div>   
  <div *ngSwitchCase="'Q'">book is Q</div>
  <div *ngSwitchCase="'K'">book is K</div>
  <div *ngSwitchDefault>default</div>
</div>
ngStyle

使用ngstyle最大的特点就是给DOM元素动态的天剑CSS属性,它有两种写法:

1.  [style.<cssproperty>]="value"的形式:

eg  :

<div [ngStyle.background-color]="'yellow'">yellow</div>

<div [ngStyle.color]="red">yellow</div>

注意:在上面的例子中我给background-color使用了单引号,而color并未使用,这是因为ngStyle是一个JavaScript对象,color是一个合法的键,不需要引号,但是background-color是一个连字符,连字符是不允许出现在对象的键名当中的,除非是一个字符串,故而使用了单引号。

2.  使用键值对的形式:键值对里面还可以使用条件语句

eg:  

 <div [ngStyle]="{color:'red',width:'10px'}"></div>

 <div [ngStyle]="{color:Codevalue?'red':'lightblue'}"></div>    亮色字体部分是一个三元表达式(常用)

ngClass

ngClass指令在HTML模板中用ngClass属性表示,可以动态设置和改变DOM元素的CSS类:

eg: 

第一种情况:普通的添加CSS类

css

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

html:

<div [ngClass]="{bordered:true}">这是带边框的box</div>

<div [ngClass]="{bordered:false}">这是没有边框的box</div>

第二种情况:设置变量动态的赋予不同的CSS类

eg:  

css: 

.bordered{ border:1px dashed #cecece }

.colored{ color:lightblue  }

html:  

<div [ngClass]="{isBordered?'bordered':'colored'}">是你有不一样的边框的呢还是我的颜色更亮丽一些的呢</div>

TS:  

export  class NgClassSampleApp {

isBordered:boolean;  //如果为true渲染出来的为有边框的字,false的话渲染为带lightblue色的字

}
ngFor

重复一个给定的DOM元素(或一组DOM元素),渲染时,每次重复都会从数组中取一个新的值,它的语法结构是:

*ngFor="let item of items ;let i= index"

  • let item 语法是用来接收items数组中的每一个元素的变量。
  • items是来自控制器的一组项的集合。
  • let i= index是为了获取数组的索引,这个跟JavaScript一样,从零开始,以此例推 。

eg:

TS: 

 this.people=[

{name:'关羽',argument:'五虎上将',country:'蜀国' },

{name:'曹操',argument:‘大帅’,country:'魏国' },

{name:'周瑜',argument:‘军师’,country:'吴国' }

]

html:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Argument</th>
      <th>Country</th>
    </tr>
  </thead>
  <tr *ngFor="let item of people">
    <td>{{item.name}}</td>
    <td>{{item.argument}}</td>
    <td>{{item.country}}</td>
  </tr>
</table>

result:

NameArgumentCountry
关羽五虎上将蜀国
曹操大帅魏国
周瑜军师吴国
ngNonBindable

这个指令一般情况下用的少,当我们在也界面中不想编译某一部分的时候,这个见例子会更好明白:

eg:

html:

<div class="noned">
  <span class="bordered">{{content}}</span>
  <span class="pre" ngNonBindable>
  ←这是{{content}}
  </span>
</div>

TS:

content:string ='王者农药';

result:

        『王者农药』  这是content;



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值