1.创建 angualr 组件
ng g component components/header
使用组件:
<app-header></app-header>
Angular数据绑定
TS文件初始化数据,html文件绑定数据
1. 绑定数据
public userinfo: any = {
username: '张三',
age: '20',
};
public msg: string = '我是msg';
<!-- 绑定数据 -->
<h3>{
{
userinfo.username}}</h3>
<h3>{
{
msg}}</h3>
2.绑定属性
<!-- 绑定属性 -->
<div title="我是一个div" style="width: 200px;height: 200px;background-color: orange;"></div>
<div style="width: 200px;height: 200px;"></div>
<div [title]=" msg" style="width: 200px;height: 200px;background-color: orange;"></div>
[ ]括起来的是绑定属性
3.绑定html
public content = '<i>我是你爸爸</i>';
<span [innerHTML]="content"></span>
4.angular还支持简单的计算
<h1>angular还支持简单的计算</h1>
<h2>1+2={
{
1+2}}</h2>
数据循环 *ngFor
示例01:
这两种定义数组的方式都是相当nice的。
// public arrs: string[] = ['一', '二', '三', '四', '五']; // 推荐写法
public arrs: Array<string> = ['一', '二', '三', '四', '五'];
<ul>
<li *ngFor="let arr of arrs">
{
{
arr}}
</li>
</ul>
示例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>
示例02:
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>
循环数据:显示索引
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>