组件中的模板
组件ts的class中定义的变量,在组件内的html中可以直接使用双大括号进行引用
绑定数据
./src/app/components/home/home.component.ts
// .......export class HomeComponent implements OnInit {title = '我是一个home组件'; // 定义一个类变量,不加修饰符默认为public。public student:object = {userName:'张三',age:15}// ..........}
./src/app/components/home/home.component.html
<!-- 使用双大括号引用组件内变量 --><h2>{{title}}</h2><h2><!-- 对象类型的也可以进行渲染 -->{{student.userName}}</h2>
ts中属性的值也可以在构造函数中进行赋值
public msg:string;constructor() {this.msg = '这是msg';console.log('studet.age=' + this.student.age);}
绑定到html属性
<div title='这是一个静态的title属性'>test1</div><!-- 使用中括号,将ts中的msg变量绑定到title属性中 --><div [title]='msg'>test2</div><!-- 使用bind-前缀绑定属性 --><img bind-src='itemImageUrl'><!-- 等同于 <img [src]='itemImageUrl'> -->
绑定html代码
在ts中定义属性:
public content:string = '<h2>这是一段html代码</h2>';
在html中获取content变量,并按html代码进行解析
不管是否为innerHTML属性,angular都不允许带有script标签的html泄露到浏览器中。
<div [innerHTML]='content'></div>
进行简单运算
<div>计算 1+2={{1+2}}计算 3+4 = {{ sum(3,4) }}</div>
在ts中定义sum方法
sum(a, b) {return a+b;}
数组循环
普通循环
在ts中定义一个数组变量arr、newsList
public arr:string[] = ['111', '222', '333'];public newsList:Array<string> = ['第一个新闻','第二个新闻','第三个新闻'];
在html中使用 ng-for 循环arr、newsListt变量:
<ol><!-- *ngFor="let 数组子项 of 数组变量" --><li *ngFor="let item of arr">{{item}}</li></ol><ol><li *ngFor="let item of newsList">{{item}}</li></ol>
对象循环
在ts中定义一个数组变量userList
public userList:any[] = [{name:'张三',age:12}, {name:'李四',age:18},{name:'王五',age:20}];
在html中使用 ng-for 循环userList变量:
<ol><li *ngFor="let item of userList">{{item.name}} 今年 {{item.age}} 岁</li></ol>
循环嵌套
在ts中定义carsList变量
public carsList:any[] = [{cate:'宝马',list:[{title:'宝马x1',price:'30万'},{title:'宝马x2',price:'32万'},{title:'宝马x3',price:'40万'}]},{cate:'奥迪',list:[{title:'奥迪q1',price:'10万'},{title:'奥迪q2',price:'22万'},{title:'奥迪q3',price:'30万'}]}];
在html中使用 ng-for 遍历汽车品牌,然后继续使用 ng-for 嵌套循环每个品牌的车型
<ul><li *ngFor="let item of carsList"><h2>{{item.cate}}</h2><ol><li *ngFor="let car of item.list">{{car.title}}价格:{{car.price}}</li></ol></li></ul>
显示数组元素的索引
快捷方式
ng-for-index
在ts中定义数组变量
public cars:any[] = [{title: '第一个新闻',desc: 'aaa'},{title: '第二个新闻',desc: 'bbb'},{title: '第三个新闻',desc: 'ccc'}];
在html中引入数组
<ul><!-- 将索引赋值给key,索引从0开始 --><li *ngFor="let item of cars; let key = index">{{key}} : {{item.title}}</li></ul>
模板引用变量
使用井号将一个dom元素声明为一个模板引用变量,该变量可以在html模板中直接使用
<label>Type something:<!-- 此处的customerInput.value中的customerInput不是ts中定义的变量,而是前面#customerInput声明的input本身 --><input #customerInput>{{customerInput.value}}</label><!-- 将模板引用变量#heroForm传递给ts组件 --><form #heroForm (ngSubmit)="onSubmit(heroForm)"> ... </form><!-- 定义的#phone模板引用变量,在整个html模板内都可以使用 --><input #phone placeholder="phone number" /><button (click)="callPhone(phone.value)">Call</button><!-- 也可以使用ref-前缀代替井号 --><input ref-fax placeholder="fax number" /><button (click)="callFax(fax.value)">Fax</button>
类型转换函数
有时候,绑定表达式可能会在AOT编译时报类型错误,并且它不能或很难指定类型,要消除这种报错,可以使用$any()转换成any类型
<p>The item's undeclared best by date is: {{$any(item).bestByDate}}</p>
