结构型指令是什么
结构型指令是塑造或重塑 DOM 的结构,比如添加、移除或维护这些元素。在anugular中最常用的3个内置结构型指令NgIf,NgFor,NgSWitch。而今天我们要介绍的主角是ngFor指令的几个常见使用。若大家想要了解更多的话,请登录官网查看并操作理解其含义。https://angular.cn/guide/structural-directives#inside-ngfor
在angular中遍历数组时,需要用到ngFor指令来给数组的每一项实例化模板。
第一种使用方式:根据索引index
<ul>
<li *ngFor="let item of menus;let i=index">
<a href="#" >
{
{item.title}}
</a>
</li>
</ul>
第二种方式:作用于首个元素first和最后一个元素last
home.component.html文件
<ul>
<li *ngFor="let item of menus;let first=first; let last =last ">
<a href="#" [class.first]="first" [class.last]="last">
{
{item.title}}
</a>
</li>
</ul>
home.component.css文件
.first{
color: yellow;
}
.last{
color: yellowgreen;
}
第三种方式:奇偶数odd和even。
home.component.html文件
<ul>
<li *ngFor="let item of menus;let odd=odd; let even=even">
<a href="#" [class.odd]="odd" [class.even]="even" >
{
{item.title}}
</a>
</li>
</ul>
home.component.css文件
.odd{
color: green;
}
.even{
color: red;
}
第四种方式:trackBy性能提升,避免大量的DOM操作,添加或删除某项是,不至于发送重绘制。
trachBy性能提升理解可以看此篇,介绍比较详细易懂:https://www.jb51.net/article/133784.htm
关于重绘及回流的理解可以查看此篇:https://segmentfault.com/a/1190000017329980
<ul>
<li *ngFor="let item of menus;let i=index;trackBy:trackByIndex">
<a href="#" [class.active]="i==selectedIndex"
(click)="handleSelection(i)">
{
{item.title}}
</a>
<span class="indicator" *ngIf="i==selectedIndex"></span>
</li>
</ul>
export class ScrollableTabComponent implements OnInit {
constructor() { }
ngOnInit(): void {}
selectedIndex=-1;
trackByIndex(index,item){
console.log(index,item);
return index
}
menus=[
{title:'angular10'},
{title:'react'},
{title:'vue'},
{title:'node'},
{title:'webpack'},
{title:'express'},
];
}