Angular开发(三)-关于属性绑定与事件绑定

一、新建一个项目工程并创建一个组件bind,如果还有不知道怎么创建angular项目的请先查看Angular2从环境搭建到开发建议直接用angular-cli创建

二、数据绑定

  • 插值的方式[比较常见],就是把利用(金甲二模板:{{ 插入的内容}})来展现component里面的数据
在bind.component.html页面中
<p>1.我是采用插值的方式的:</p>
<span>{{title}}</span>
  • 1
  • 2
  • 3
在bind.component.ts文件中
....
export class BindComponent implements OnInit {
  title:string = "我是子组件插值的方式显示的";
  ....
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 属性绑定 
    • 使用金甲二的模板插入值
    • 使用[属性]=“值”进行属性绑定(属性如果不加[],那么就直接是传统的赋值,加上[]就是angular中属性绑定)
<p>2.属性绑定:</p>
<img src="{{src}}"/>
<p>3.属性绑定:</p>
<img [src]="src"/>
  • 1
  • 2
  • 3
  • 4
biind.component.ts文件代码
src:string = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
  • 1
  • 2
  • 3
  • 事件绑定 
    事件绑定
<p>4.事件绑定:</p>
<input type="button" value="按钮" (click)="info($event)"/>
  • 1
  • 2
bind.component.ts文件
info(event:any){
   console.log(event);
 }
  • 1
  • 2
  • 3
  • 4

三、DOM绑定与HTML属性绑定的区别

- DOM绑定 HTML绑定
相同情况下 一个元素的id  
有html属性无dom属性   表格中td的colspan
有dom属性无html属性 textContent属性  
关于值 dom表示当前值 html表示初始化值
关于可变 dom值是可变的 html值是不可变的

总结:我们模板绑定是通过DOM属性来操作的,不是HTML属性来操作的

四、HTML绑定

table style="border-collapse:collapse" border="1" width="100%">
  <tr>
    <td>第一个</td>
    <td>第二个</td>
  </tr>
  <tr>
    <td [attr.colspan]="sizeNum">我占2格子</td>
  </tr>
</table>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

五、class类的绑定

  • 直接使用[class]DOM绑定会覆盖之前的class
<div class="a b" [class]="classname"></div>
//bind.component.ts文件
classname:string = "c";
  • 1
  • 2
  • 3
  • 使用[class.类名]=”boolean”来判断是否追加这个class
<div class="a b" [class.c]="isShow"></div>
//bind.component.ts文件
isShow:boolean = true;
  • 1
  • 2
  • 3
  • 使用对象显示
<div [ngClass]={a:isA,b:isB,c:isC}></div>
//bind.component.ts文件
isA:boolean = true;
isB:boolean = true;
isC:boolean = true;
//或者
<div [ngClass]="classGroup"></div>
//bind.component.ts文件
classGroup:any = {
    a:true,
    b:true,
    c:true
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

六、样式绑定

  • 绑定单个样式
<p [style.color]="isRed?'red':'blue'">我是测试样式的</p>
<p [style.color]="redColor">我是测试样式的</p>
//bind.component.ts文件
isRed:boolean = true;
redColor:string = "red";
  • 1
  • 2
  • 3
  • 4
  • 5
  • 带单位的
<p [style.font-size.em]="fontSize?1:3">我是测试样式的</p>
//bind.component.ts
fontSize:boolean = false;
  • 1
  • 2
  • 3
  • 绑定多个样式
<div [ngStyle]="styleGroup"></div>
//bind.component.ts
styleGroup:any = {
  width:"100px",
  height:"100px",
  border:"1px solid #ddd",
  margin:"20px"
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

七、双向绑定

双向绑定仅仅是之前的属性绑定与事件绑定的结合,所以是[(ngModel)]=”“

<p>双向数据绑定:</p>
<input type="text" [(ngModel)]="user.name"/>
<div [ngStyle]="style1">{{user.name}}</div>
//ts代码
user:any = {
    name:""
  }

猜你喜欢

转载自blog.csdn.net/IronKee/article/details/81183523