angular no access to object.id

Viewed 177

hey i just started with angular and my problem is, why i have no access to my .id,.name and .color, the first code is my oberteile-names.ts where i have defined my const array


import { Oberteil } from './oberteile/oberteil';

export const OBERTEILE: Oberteil[] = [
    {id:11, name: 'flannelshirt', color: 'vintagebrown'},
    {id:12, name: 'flannelshirt', color: 'vintagegreen'},
    {id:13, name: 'flannelshirt', color: 'vintagewhite'},
    {id:14, name: 'cordhemd', color: 'black'},
    {id:15, name: 'cordhemd', color: 'vintagebrown'},
    {id:16, name: 'cordhemd', color: 'vintagegreen'},
    {id:17, name: 'basicshirt', color: 'black'},
    {id:18, name: 'basicshirt', color: 'white'}




]; 

here is my simple oberteil.ts

export interface Oberteil {
    id: number;
    name: string;
    color : string;
}

so now i go into my oberteile.component.ts and initialize oberteil with the const OBERTEILE

import { Component, OnInit } from '@angular/core';
import { OBERTEILE } from '../oberteil-names';

@Component({
  selector: 'app-oberteile',
  templateUrl: './oberteile.component.html',
  styleUrls: ['./oberteile.component.css']
})
export class OberteileComponent implements OnInit {
  oberteil = OBERTEILE;
 
  constructor() { }

  ngOnInit(): void {
    
  }


}

now i want to display them on my oberteile.component.html but i have no access to id

<h2>{{oberteil.id}}</h2>

i think it is very easy to be solved but i can not find any answers for it, even when i just want to display {{oberteile}}, it just display [object,Object]

3 Answers

oberteil is an array of multiple elements. You need to select a specific element of the array, or iterate over the array with *ngFor:

<h2>{{oberteil[0].id}}</h2><!-- display the ID of the first element -->
<h2 *ngFor="let element of oberteil">{{element.id}}</h2><!-- display IDs of all elements -->

oberteil is an array. You can't access it like that. You need to specify the index of the array.

Or if you are trying to show the id from each element of oberteil array, you can use *ngFor directive.

<h1 *ngFor="let o of oberteil">{{o.id}}</h1>

See *ngFor

oberteil is array, no Object, so you cannot bind the value with <h2>{{oberteil.id}}</h2> It should be like that in *ngFor iteration to get all values

<div *ngFor="let item of oberteil">
  <p>{{item.id}}</p>
  <p>{{item.name}}</p>
  <p>{{item.color}}</p>
</div>

It is just example to use your oberteil variable in html to bind the data.

Related