使用Angular的内置管道keyvalue,用法如下
<!-- test.component.html -->
<div class="pipe">
//循环对象
<div *ngFor="let item of obj | keyvalue">
{{item.key}}: {{item.value}}
</div>
//循环map数据结构
<div *ngFor="let item of map | keyvalue">
{{item.key}}: {{item.value}}
</div>
</div>
// test.component.ts
export class TestComponent implements OnInit {
obj:{[key: number]: string} = {2: 'foo', 1: 'bar'}; //定义一个对象
map = new Map([[2, 'foo'], [1, 'bar']]); //定义一个map结构
}
总结:keyvalue可以用来循环对象和map结构,直接用即可,因为这是内置管道。其他的常用内置管道如下
Angular有很多内置管道供我们使用,下面是常用的内置管道:
AsyncPipe --自动订阅模板中的Observable或Promise
CurrencyPipe --把数字转换成金额字符串, 根据本地化规则进行格式化
DatePipe --根据区域设置规则格式化日期值
DecimalPipe --数字转字符串,并可以指定格式
KeyValuePipe --使ngFor可以循环Object或Map对象
JsonPipe --把一个值转换成JSON字符串格式。在调试时很有用。
TitleCasePipe --把首字母大写,其它小写
SlicePipe --截取Array或String
PercentPipe --数字转百分比
LowerCasePipe和UpperCasePipe --转化小写或大写