Angular2样式绑定

1、[style.propetyName]

a. 基本用法

//template
<p [style.fontSize]='fSize'></p>
<p [style.width.px]='width200'></p>    //带单位

//component.ts
fSize: string='14px';
width200: string='200';

b. 绑定函数

//template
<p [style.height]="setHeight(list.length)"></p>   

 //component.ts
setHeight(length) {
  if(length==1){
      return '4rem';
  }
  else if(length==2){
      return '6rem';
  }
  else{
      return '10rem';
  }
}

2、[ngStyle]

a. 基本用法

//template
<p [ngStyle]="eleStyle"></p>

//component.ts
eleStyle: any={
      fontSize:'14px';
      color:'#333';
 }

b. 对象型写法

<p [ngStyle]="{'background': '#ff0'}"></p>   

c. 判断添加

<p [ngStyle]="{'background': userName=='xjy'?'red':'green'}"></p>     

3、[class.className]

//template
<p [class.changeColor]="flag"></p>

//component.ts
flag: boolean=true

//css
changeColor: { color:'#fff'; }

4、[ngClass]

a. 基本用法

//template 
<p [ngClass]="{'title':true}"></p>   //第一个参数是类名,第二个参数是boolean值
//css
.title{ color: '#333'; }

b. 判断

//template
<p [ngClass]="{'bgColor': userName=='xjy' }"></p>
//css
.bgColor{ background: '#f00'; }

c. 绑定函数

//template 
<p [ngClass]="getIco(menuCode)"></p>
//component.ts
getIco(menuCode){
   let className="";
   switch (menuCode)
   {
     case 'index':
     className= "index";
     break;
     case 'view':
     className= "view";
     break;
     case 'operation':
     className= "operation";
     break;
    };
   return className;
}

猜你喜欢

转载自blog.csdn.net/qq_37012533/article/details/85092306