1. Angular 组件、数据绑定和数据循环
1.1 创建 angualr 组件
ng g component components/news
使用组件:
<app-news></app-news>
1.2 Angular数据绑定
TS文件初始化数据,html文件绑定数据
1.2.1 绑定数据
/*
声明属性的几种方式:
public 共有 *(默认) 可以在这个类里面使用、也可以在类外面使用
protected 保护类型 他只有在当前类和它的子类里面可以访问
private 私有 只有在当前类才可以访问这个属性
*/
public userinfo: any = {
username: '张三',
age: '20',
};
public msg: string = '我是msg';
<!-- 绑定数据 -->
<h3 style="color: orange;">{{userinfo.username}}</h3>
<h3 style="color: orange;">{{msg}}</h3>
运行结果:
1.2.2 绑定属性
<!-- 绑定属性 -->
<div title="我是一个div" style="width: 200px;height: 200px;background-color: orange;"></div>
<div style="width: 200px;height: 10px;"></div>
<div [title]="msg" style="width: 200px;height: 200px;background-color: orange;"></div>
[ ]括起来的是绑定属性
运行结果:
1.2.3 绑定html
public content = '<i>我是你爸爸</i>';
<span [innerHTML]="content"></span>
运行结果:
1.3 angular还支持简单的计算
<h1>angular还支持简单的计算</h1>
<h2>1+2={{1+2}}</h2>
运行结果:
1.4 数据循环 *ngFor
1.4.1 示例01:
这两种定义数组的方式都是相当nice的。
// public arrs: string[] = ['一', '二', '三', '四', '五']; // 推荐写法
public arrs: Array<string> = ['一', '二', '三', '四', '五'];
<ul>
<li *ngFor="let arr of arrs">
{{arr}}
</li>
</ul>
1.4.2 示例02:
public userlist:any[]=[{
username:'张三',
age:20
},{
username:'李四',
age:21
},
{
username:'王五',
age:40
}];
<ul>
<li *ngFor="let item of userlist">
{{item.username}}-------{{item.age}}
</li>
</ul>
1.4.3 示例03:
public cars: any[] = [
{
cate: '宝马',
list: [
{
title: '宝马x1',
price: '30万',
},
{
title: '宝马x2',
price: '30万',
},
{
title: '宝马x3',
price: '40万',
},
],
},
{
cate: '奥迪',
list: [
{
title: '奥迪q1',
price: '40万',
},
{
title: '奥迪q2',
price: '40万',
},
{
title: '奥迪q3',
price: '30万',
},
],
},
];
<ul>
<li *ngFor="let item of cars">
<b>{{item.cate}}</b>
<ol>
<li *ngFor="let car of item.list">
<i>{{car.title}}</i>-----<i>{{car.price}}</i>
</li>
</ol>
</li>
</ul>
1.4.4 循环数据:显示索引
public list: any[] = [
{ title: '我是新闻01' },
{ title: '我是新闻02' },
{ title: '我是新闻03' },
{ title: '我是新闻04' },
{ title: '我是新闻05' },
];
<h1>循环数据,显示数据的索引值(key)</h1>
<ul>
<li *ngFor="let item of list; let key = index">
{{key}} --> {{item.title}}
</li>
</ul>