Looking to display specific object properties based on predefined keys in an array? Here's an example using TypeScript:
const dataObject: IData = { a: 1, b: 2, c: 3 };
const dataKeys: string[] = ['a', 'c'];
dataKeys.forEach((key: string): void => { console.log(dataObject[key]); })
To achieve this in Angular, you can use the following code:
Angular template:
<ng-container *ngFor="let key of dataKeys">
{{ dataObject[key] }}
</ng-container>
And in your Angular component:
type DataKeys = Array<keyof IData>;
public dataObject: IData = { a: 1, b: 1 };
public dataKeys: DataKeys = ['a', 'b'];
If you encounter an error like "error TS7052" while compiling Angular code, it might be due to the lack of an index signature in type 'IData'. However, you can handle this within the component as shown below without any issues:
this.dataKeys.forEach((column: keyof IData): void => {
console.log(this.dataObject[column]);
});
Feel free to reach out if you need further assistance on resolving the above issue.