Angular 使用keyvalue管道访问特定的键/值对
我在Angular 11中使用keyvalue管道循环通过从Http请求获得的对象。问题是,在我的模板中,我只想显示特定的键值对,而不想显示整个对象包含的内容 例如,我有一个对象:Angular 使用keyvalue管道访问特定的键/值对,angular,object,pipe,Angular,Object,Pipe,我在Angular 11中使用keyvalue管道循环通过从Http请求获得的对象。问题是,在我的模板中,我只想显示特定的键值对,而不想显示整个对象包含的内容 例如,我有一个对象: agreedToTermsOfUse: true comments: "" companyId: "20097" contactId: "20127" createDate: 1617793054388 ctCollectionId: "0&quo
agreedToTermsOfUse: true
comments: ""
companyId: "20097"
contactId: "20127"
createDate: 1617793054388
ctCollectionId: "0"
defaultUser: false
emailAddressVerified: true
externalReferenceCode: ""
facebookId: "0"```
and I only want to show companyId and contactId.
The code in my template is the following:
<button type="button" (click)="getData()">Click me</button>
<div *ngFor="let item of dataObject | keyvalue">
<b>{{item.key}}</b> : {{item.value}}
</div>
and shows the whole content of the object.
agreedToTermsOfUse:true
评论:“”
公司名称:“20097”
联系人ID:“20127”
创建日期:1617793054388
ctCollectionId:“0”
defaultUser:false
emailAddressVerified:正确
外部引用代码:“
facebookId:“0”```
我只想显示公司ID和联系人ID。
我的模板中的代码如下所示:
点击我
{{item.key}}:{{item.value}
并显示了对象的全部内容。
您不需要*ngFor循环,然后。。。
打印
{{dataObject.companyId}} {{dataObject.contactId}}
访问对象属性可能更简单,但如果仍要使用*ngFor循环,请创建一个自定义管道,将对象转换为数组并过滤所需的键
import { Pipe, PipeTransform } from '@angular/core';
interface IKeyValuePair {
key: string;
value: string;
}
const validKeys = ['companyId', 'contactId'];
@Pipe({
name: 'keyValueFilter'
})
export class KeyValueFilterPipe implements PipeTransform {
transform(value: any): Array<IKeyValuePair> {
return Object.keys(value).reduce((acc: Array<IKeyValuePair>, key) => {
if (validKeys.includes(key)) {
acc.push({ key, value: value[key] });
}
return acc;
}, []);
}
}
从'@angular/core'导入{Pipe,PipeTransform};
接口IKeyValuePair{
键:字符串;
值:字符串;
}
const validKeys=['companyId','contactId'];
@烟斗({
名称:“keyValueFilter”
})
导出类KeyValueFilterPipe实现PipeTransform{
变换(值:任意):数组{
返回Object.keys(value).reduce((acc:Array,key)=>{
if(有效期包括(密钥)){
acc.push({key,value:value[key]});
}
返回acc;
}, []);
}
}
像这样使用它
<div *ngFor="let item of dataObject | keyValueFilter">
<b>{{item.key}}</b> : {{item.value}}
</div>
{{item.key}}:{{item.value}