How to display enum array in Angular?
I have an object with a enum array property and i want display in a html-component:
<ul class="list-group list-group-flush">
<li *ngFor="let prop of object.characteristics" class="list-group-item">
{{ prop }}
</li>
</ul>
My characteristics value is = [Calm,Sozial,Fearful,Protective,Friendly]
I tried with object?.characteristics,
If I use {{object.characteristics}}, then it works: Calm,Sozial,Fearful,Protective,Friendly
In this case it works, I think it has something to do with route in app.module.ts:
const routes: Routes = [
{path: 'object/:id', component: DetailComponent},
{path: 'objects', component: ListComponent},
...
{ path: '', redirectTo: 'objects', pathMatch: 'full' },
{ path: '**', redirectTo: '/objects', pathMatch: 'full' }
Although the other properties are displayed, the object will not recognized:
<ul class="list-group list-group-flush" *ngIf="object">
<li *ngFor="let prop of tempObject.characteristics" class="list-group-item">
{{ prop }}
</li>
</ul>
But I want to use a *ngFor Attribute
2
Could you share how you’ve defined your enum array for more clarity?
This seems to work for me :
import { Component } from '@angular/core';
export enum Characteristic {
Calm = 'Calm',
Social = 'Social',
Fearful = 'Fearful',
Protective = 'Protective',
Friendly = 'Friendly',
}
@Component({
selector: 'app-sample-component',
template: `
<ul class="list-group list-group-flush">
<li *ngFor="let prop of object.characteristics" class="list-group-item">
{{ prop }}
</li>
</ul>
`,
})
export class SampleComponent {
object = {
characteristics: [
Characteristic.Calm,
Characteristic.Social,
Characteristic.Fearful,
Characteristic.Protective,
Characteristic.Friendly,
],
};
}
dxxhsi97 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5
Now I am sure, what the problem was, but I needed two steps:
- The problem was in routes:
… { path: ‘/puppy/{id’}, component: PuppyDetailsComponent },
…
I confused {id} parameter from SpringBoot with :id from Angular
- a new file component.module.ts was created:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DetailComponent } from './detail.component'; import { ListComponent } from '../list/list.component'; import { RouterModule, ActivatedRoute, Routes } from '@angular/router'; @NgModule({ declarations: [DetailComponent], imports: [CommonModule, RouterModule], exports: [DetailComponent] }) export class ComponentModule { }
After that, everything worked out right