Angular数据循环 *ngFor 与 条件判断 *ngif 和 *ngSwitch
首先,进行Angular环境的搭建和项目创建
ctrl + c 结束服务
1、新建模块
ng g component components/home
如图:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CpTKDRYZ-1644311674363)(C:\Users\17216\AppData\Roaming\Typora\typora-user-images\image-20220207163634085.png)]](https://i-blog.csdnimg.cn/blog_migrate/ae96bc345ebe04d470c1e24f782e1b17.png)
2、将home模块添加到主页
app.component.html,页面代码如下,没有看错,只有一行
<app-home></app-home>
3、Angular数据循环 *ngFor
1)home.component.ts中定义任意类型的数组
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
//定义一个数组
public list:any[]=[
{
"title":'happy day'
},{
"title":'good days'
},{
"title":'exciting days'
}
]
constructor() { }
ngOnInit(): void {
}
}
2)编辑 home.component.html,内容如下
<h1>数据循环并显示数据的索引</h1>
<h2>数据循环</h2>
<ul>
<li *ngFor="let item of list">
{{item.title}}
</li>
</ul>
<h2>数据循环并显示数据索引</h2>
<ul>
<li *ngFor="let item of list;let key=index;">
{{key}}---{{item.title}}
</li>
</ul>
3) 启动服务 ,终端输入
ng serve --open
4)运行结果如图所示
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yYeCxG3g-1644311674366)(C:\Users\17216\AppData\Roaming\Typora\typora-user-images\image-20220207211918943.png)]](https://i-blog.csdnimg.cn/blog_migrate/77a29a1b57a8eee62bf977a711b6a2a9.png)
4、angular条件判断 *ngif 和 *ngSwitch
1)home.component.ts新定义两个变量
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
//定义一个任意类型的数组
public list:any[]=[
{
"title":'happy day'
},{
"title":'good days'
},{
"title":'exciting days'
}
]
//定义一个bollean类型的变量
public flag:boolean=true;
//定义一个number类型的变量
public num:number=2; //num为1时,输出“你好世界”; num为2时,输出“have a good day!”
constructor() { }
ngOnInit(): void {
}
}
2)编辑 home.component.html,内容如下
<h1>数据循环并显示数据的索引</h1>
<h2>数据循环</h2>
<ul>
<li *ngFor="let item of list">
{{item.title}}
</li>
</ul>
<h2>数据循环并显示数据索引</h2>
<ul>
<li *ngFor="let item of list;let key=index;">
{{key}}---{{item.title}}
</li>
</ul>
<hr>
<h1>条件判断语句 *ngIF 和 *ngSwitch</h1>
<h2>条件判断语句*ngIF</h2>
<div *ngIf="flag">
条件为真
</div>
<div *ngIf="!flag">
条件为假
</div>
<h2>条件判断语句 *ngSwitch</h2>
<div [ngSwitch]="num">
<div *ngSwitchCase="1">
你好世界
</div>
<div *ngSwitchCase="2">
have a good day
</div>
</div>
运行结果如图:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QPGuMUr5-1644311674368)(C:\Users\17216\AppData\Roaming\Typora\typora-user-images\image-20220207212211715.png)]](https://i-blog.csdnimg.cn/blog_migrate/114c20de56f59b6ee424819f2110dc04.png)
这篇博客介绍了在Angular中如何使用模板指令进行数据循环(*ngFor)和条件判断(*ngIf, *ngSwitch)。首先,博主创建了一个新的Angular模块并将其添加到主页。接着,在home.component.ts中定义了数组,并在home.component.html中使用*ngFor进行数据循环展示。随后,博主展示了如何在ts文件中定义变量,并在html模板中使用*ngIf和*ngSwitch进行条件判断。最后,给出了运行结果。"
113335633,10535383,手动更新Android设备设置,"['安卓开发', '数据库管理', 'sqlite', '设备配置']
379

被折叠的 条评论
为什么被折叠?



