jsonangularobjectngfor

Accessing an object passed from the component in Angular 2


I have the following class named Enumeration:

export class Enumeration {
    name: string;
    values: Object;
}

Now, in my component I have created my object and filled with data.

In this template I have something like this:

<div class="card-item-content">
  <span>{{enumeration | json}}</span>
</div>

this works normaly and I can see this:

{ "name": "employee-type", "values": [ null, { "id": 1, "text": "Employee" }, { "id": 2, "text": "Contractor" }, { "id": 3, "text": "Newjoiner" }, null, { "id": 5, "text": "Consultant" }, { "id": 6, "text": "GCP" }, { "id": 7, "text": "Career Counselor" } ] }

but when I try

{{enumeration.name | json}} or {{enumeration.values | json}}

I got this error message:

Cannot read property 'name' of undefined

when I do :

*ngFor="let enum of enumeration.values"

it will loops 8 times, but first span is empty then it goes 3 times with

[object Object] 

and then another one empty span, and then 3 times previous.

The point is, I want to access for each not null objects in values object property , propertyies text and id.

So, the result should be 6 spans with this content:

Employee 1
Contractor 2
Newjoiner 3
Consultant 5
GCP 6
Career Counselor 7

Can anybody give me some hints please?

UPDATE - SOLVED:

So, I did it this way only in template.

<ng-container *ngFor="let enum of enumeration?.values">
   <span *ngIf="enum">{{enum?.text}} : {{enum?.id}}</option>
</ng-container>

This is my ngOnInit:

 ngOnInit() {
    if (this.id != null) {
      const enumName = employeeDetailsEnumMapping.get(this.id);
      this.enumsService.getEnums().subscribe(data => {
        this.enumeration = data.get(enumName);
        if (this.enumeration == null) {
          console.error(`missing enum ${this.id}`);
        }
      });
    }
  }

and when I added:

this.enumeration.values = this.enumeration.values.filter(x => x != null);

it says:

'filter' property does not exist on type 'Object';

This helped me to solve this problem. But actually, the filter way would look better, I guess.


Solution

  • What I guess you want is to remove all null values from the array, so that you can properly access the objects in the array, so you could do this for example in your subscribe:

    .subscribe(data => {
      this.enumeration = data;
      this.enumeration.values = this.enumeration.values.filter(x => x != null);        
    })
    

    Then your iteration should work fine, using the safe navigation operator to safeguard null values (if this is async)

    <div *ngFor="let enum of enumeration?.values">
      {{enum.text}}
    </div>
    

    Demo