首页 > 解决方案 > 试图打印一个包含对象数组的对象 Html

问题描述

我正在尝试打印此对象:

export class Ricette {
    nome: string;
    azioni: {tempo: number, azione: string}[][]
  }
export const RICETTE : Ricette[] = [
    {
        nome: 'Alici',
        azioni: [[
            {tempo: 500, azione: 'scongela'},
            {tempo: 60, azione: 'nulla'}        
        ]]
    },
    {
        nome: 'Baccalà',
        azioni: [[
            {tempo: 500, azione: 'scongela'}],
            [
                {tempo: 210, azione: 'immerso'},
                {tempo: 210, azione: 'cestello su'},
                {tempo: 30, azione: 'immerso'}
            ]        
        ]
    },
    {
        nome: 'Hamburger',
        azioni: [[
            {tempo: 500, azione: 'scongela'}],
            [
                {tempo: 210, azione: 'immerso'},
                {tempo: 210, azione: 'cestello su'},
                {tempo: 30, azione: 'immerso'}
            ]        
        ]
    }
];
ricette = RICETTE;

在一个 html 文件中。

数组azioni[]将在 的每个项目中具有不同的长度ricette

我该怎么做才能在 html <'ul><'li><'/li><'/ul> 中打印对象?

标签: htmlarraysangulartypescript

解决方案


您可以添加父 div*ngFor以显示数组的所有值,如下所示:

  <div *ngFor="let ricetta of ricettaArray">
        <h2>{{ricetta.nome}}:</h2>
        <div>
            <span>Nome-> </span>{{ricetta.nome}}</div>
            <ul *ngIf="ricetta?.azioni && ricetta?.azioni.length > 0">
                <li *ngFor="let item of ricetta?.azioni ; let i = index" [attr.data-index]="i">
                    {{item?.tempo}}
                    {{item?.azione}}
                </li>
            </ul>
    </div>

ricettaArray 声明如下所示:

 ricettaArray : Ricette[] = [];

  let r1 = {
      nome: 'Alici',
      azioni: [
        {tempo: 500, azione: 'scongela'},
        {tempo: 60, azione: 'nulla'}]
    };
    let r2 = {
      nome: 'Blici',
      azioni: [
        {tempo: 400, azione: 'bcongela'},
        {tempo: 50, azione: 'bulla'},
        {tempo: 500, azione: 'bulldsfa'}]
    };
    this.ricettaArray.push(r1);
    this.ricettaArray.push(r2);

推荐阅读