Search code examples
angulartypescriptkey-value

Angular keyvalue pipe and looping trough 2 objects


I am trying to refactor some code I have inherited but not quite sure to understand how. In my ts file I am declaring the object of the keys I want to include:

keysInclude = {
property1: 'Property 1',
property2: 'Property 2',
property3: 'Property 3',
}

myObject = {
property1: 'some string',
property2: 'some string',
property3: 'some string',
property4: 'some property I don't want to show'
property5: 'some property I don't want to show'
}

then in my template I have this part of the code

<div *ngFor = " let keyValuePair of keysInclude | keyvalue; let i=index">
<span>{{keyValuePair.value}}</span>
<span>{{myObject[keyValuePair.key]}}</span>
<span></span>
</div>

I am struggling to type my keysInclude, Ideally I would like add the types without refactoring much but I am afraid that I don't really understand how to do it. myObject type will always be defined and will always have same properties as my keys inside keysInclude object . I have tried to use Record and also KeyValue interface of Angular but I always have errors that my Element implicitly has an 'any' type because expression of type {} cant be used to index myObject.


Solution

  • You can use keyof (to infer your type keys) in combination with Partial (to ba able to specify a subgroup of the keys to be shown) to achieve what you want like this:

    
    keysInclude: { [Key in keyof Partial<MyObjectType>]: string } = {
      property1: 'Property 1',
      property2: 'Property 2',
      property3: 'Property 3',
    };