programing

* ngFor를 사용하여 객체 키를 반복하는 방법

sourcetip 2021. 1. 16. 11:17
반응형

* ngFor를 사용하여 객체 키를 반복하는 방법


Angular 2에서 * ngFor를 사용하여 [객체 객체]를 반복하고 싶습니다

. 문제는 객체가 객체의 배열이 아니라 추가 객체를 포함하는 객체의 객체라는 것입니다.

{

  "data": {
    "id": 834,
    "first_name": "GS",
    "last_name": "Shahid",
    "phone": "03215110224",
    "role": null,
    "email": "test@example.com",
    "picture": **{ <-- I want to get thumb: url but not able to fetch that**
      "url": null,
      "thumb": {
        "url": null
      }
    },
    "address": "Nishtar Colony",
    "city_id": 2,
    "provider": "email",
    "uid": "test@example.com"
  }
}

파이프를 사용하여 객체를 반복 할 수 있다는 것을 알고 있지만 객체에서 객체로 더 반복 할 수있는 방법은 data-> picture-> thum : url을 의미 합니다.


각도 6.0.0

https://github.com/angular/angular/blob/master/CHANGELOG.md#610-2018-07-25

도입 KeyValuePipe

참조 https://angular.io/api/common/KeyValuePipe

@Component({
  selector: 'keyvalue-pipe',
  template: `<span>
    <p>Object</p>
    <div *ngFor="let item of object | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
    <p>Map</p>
    <div *ngFor="let item of map | keyvalue">
      {{item.key}}:{{item.value}}
    </div>
  </span>`
})
export class KeyValuePipeComponent {
  object: {[key: number]: string} = {2: 'foo', 1: 'bar'};
  map = new Map([[2, 'foo'], [1, 'bar']]);
}

실물

파이프를 사용할 수 있습니다.

@Pipe({ name: 'keys',  pure: false })
export class KeysPipe implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value)//.map(key => value[key]);
    }
}
<div *ngFor="let key of objs | keys">

* ngFor를 사용하여 객체 키를 반복하는 방법 도 참조하십시오 .


이를 수행하는 가장 우아한 방법은 다음 Object.keys과 같이 자바 스크립트를 사용하는 것입니다.

구성 요소에서 개체를 템플릿으로 전달합니다.

Object = Object;

그런 다음 템플릿에서 :

<div *ngFor="let key of Object.keys(objs)">
   my key: {{key}}
   my object {{objs[key] | json}} <!-- hier I could use ngFor again with Object.keys(objs[key]) -->
</div>

사용자 지정 파이프를 만들어야합니다.

import { Injectable, Pipe } from '@angular/core';
@Pipe({
   name: 'keyobject'
})
@Injectable()
export class Keyobject {

transform(value, args:string[]):any {
    let keys = [];
    for (let key in value) {
        keys.push({key: key, value: value[key]});
    }
    return keys;
}}

And then use it in your *ngFor

*ngFor="let item of data | keyobject"

I know this question is already answered but I have one solution for this same.

You can also use Object.keys() inside of *ngFor to get required result.

I have created a demo on stackblitz. I hope this will help/guide to you/others.

CODE SNIPPET

HTML Code

<div *ngFor="let key of Object.keys(myObj)">
  <p>Key-> {{key}} and value is -> {{myObj[key]}}</p>
</div>

.ts file code

Object = Object;

myObj = {
    "id": 834,
    "first_name": "GS",
    "last_name": "Shahid",
    "phone": "1234567890",
    "role": null,
    "email": "test@example.com",
    "picture": {
        "url": null,
        "thumb": {
            "url": null
        }
    },
    "address": "XYZ Colony",
    "city_id": 2,
    "provider": "email",
    "uid": "test@example.com"
}

1.Create a custom pipe to get keys.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return Object.keys(value);
  }
}
  1. In angular template file, you can use *ngFor and iterate over your object object
<div class ="test" *ngFor="let key of Obj | keys">
    {{key}}
    {{Obj[key].property}
<div>

If you are using a map() operator on your response,you could maybe chain a toArray() operator to it...then you should be able to iterate through newly created array...at least that worked for me :)


Angular now has a type of iterate Object for exactly this scenario, called a Set. It fit my needs when I found this question searching. You create the set, "add" to it like you'd "push" to an array, and drop it in an ngFor just like an array. No pipes or anything.

this.myObjList = new Set();

...

this.myObjList.add(obj);

...

<ul>
   <li *ngFor="let object of myObjList">
     {{object}}
   </li>
</ul>

i would do this:

<li *ngFor="let item of data" (click)='onclick(item)'>{{item.picture.url}}</li>

ReferenceURL : https://stackoverflow.com/questions/41396435/how-to-iterate-object-keys-using-ngfor

반응형