Angular(2)
绑定数据
-
定义数据
定义数据在.ts 文件中
声明属性的几种方式:public、protected、private,默认都是 public。private 只能在当前类中使用;protected 只有在当前类和他的子类中可以用;public 可以在类内和类外中使用。
声明属性不要用var
、let
、const
,声明了就变成变量了。//定义数据的几种方式 public title = 'I am a title of news.'; content = 'I am the content fo news'; username:string = 'olivia'; public student:string = 'I am the data of a student.' //推荐使用这种方式
定义对象:
public userInfo:any = {//这里很奇怪,如果写object会报错。写any解决问题。 username:"olivia" age:'23' }
数据类型如果不写就是 any,写了如果值并不是该类型会报错。可以只定义,不赋值,可以通过构造函数或者方法访问属性,通过 this。已经定义的属性,也可以通过构造函数或者方法改变的属性的值。
-
绑定数据
绑定数据在 html 文件中<h1>{{title}}</h1> <h1>{{content}}</h1> <h1>{{username}}</h1> <h1>{{student}}</h1> <h1>{{userInfo.username}}</h1>
绑定属性
操作之后在鼠标移到该 div 是会显示出 title 的内容。如果动态的数据需要加中括号。
```html
<div title="我是一个div">鼠标移上去看一下</div>
<div [title]="student">olivia</div>
```
绑定 html
```javascript
public con="<h2>我是一个html标签</h2>"
```
```html
<div>{{con}}</div> <!--原样输出-->
<div [innerHTML]='con'></div> <!--仅输出html标签内部的内容-->
```
Angular 模板简单运算
```html
1+2 = {{1+2}}
```
Angular 的数据循环 *ngFor
-
普通数组的循环
//定义数组的方法 public arr = ['111','222','333'] public arr1:any[] = ['111','222','333'] //推荐这么写! public arr2:Array<string> = ['111','222','333'] //<>中制定了数组中每个元素的类型,如果不是这个类型,会报错
<ol> <li *ngFor="let item of arr">{{item}}</li> </ol>
-
包含对象的数组的循环
public userlist:any[] = [{ username:'Jack', age:20 },{ username:'Tom', age:24 },{ username:'Mary', age:17 }]
<ol> <li *ngFor="let item of userlist">{{item.username}}------{{item.age}}</li> </ol>
-
包含 list 的对象组成的数组的循环
public carlist:any[] = [ { cate:"宝马", list:[ { title:"宝马x1", price:"100w" }, { title:"宝马x2", price:"50w" }, { title:"宝马x3", price:"80w" } ]}, { cate:"奥迪", list:[ { title:"奥迪 Q7", price:"120w" }, { title:"奥迪 Q8", price:"150w" }, { title:"奥迪 Q6", price:"60w" } ]} ]
<ul> <li *ngFor="let item of carlist"> <h2>{{item.cate}}</h2> <ol> <li *ngFor="let car of item.list">{{car.title}}------{{car.price}}</li> </ol> </li> </ul>