angular无法访问object.id



嘿,我刚从angular开始,我的问题是,为什么我不能访问我的.id、.name和.color,第一个代码是我的oberteile-names.ts,我在那里定义了我的const数组


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'}


]; 

这是我的简单oberteil.ts

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

所以现在我进入我的oberteile.component.ts,用常量OBERTILE 初始化oberteil

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 {

}

}

现在我想在我的oberteile.component.html上显示它们,但我无法访问id

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

我认为它很容易解决,但我找不到任何答案,即使我只想显示{{oberteile}},它也只显示〔object,object〕

oberteil是一个由多个元素组成的数组。您需要选择数组的特定元素,或者使用*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是一个数组。你不能那样访问它。您需要指定数组的索引。

或者,如果您试图从oberteil数组的每个元素中显示id,则可以使用*ngFor指令。

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

参见*ng

oberteil是数组,没有Object,因此不能将值与<h2>{{oberteil.id}}</h2>绑定它应该像*ngFor迭代中那样获得所有值

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

这只是在html中使用oberteil变量绑定数据的示例。

最新更新