Accessing an object passed from the component in Angular 2

Discussão em 'Angular' iniciado por Martin Fric, Novembro 9, 2024.

  1. Martin Fric

    Martin Fric Guest

    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.

    Continue reading...

Compartilhe esta Página