【问题标题】:Print an array element in JSON object in Angular在 Angular 中打印 JSON 对象中的数组元素
【发布时间】:2019-04-17 13:33:47
【问题描述】:

我创建了一个 Angular 组件来打印一些 JSON 对象数据。

Component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {

  name = 'Angular';

  obj = {
    id:1,
    title:"student",
    name:"ABC",
    subjects: [
      { sub_id: 1, sub_name: 'Maths'},
      { sub_id: 2, sub: 'physics' },
      { sub_id: 3, sub: 'chemistry'}
    ]
  };

  constructor(){ }      
}

我需要以 HTML 格式打印所有主题名称。所以我这样做了

component.html

<p *ngFor="let item of obj['subjects']">{{ item.sub_name }}</p>

但是打开页面后,控制台报错!我认为错误在for循环中,但我无法弄清楚。我在这里错过了什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您的属性名称是obj,但您使用了array

    <p *ngFor="let item of obj.subjects">{{ item.sub_name }}</p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      相关资源
      最近更新 更多