首页 > 解决方案 > 将JSON数组传递给Angular中的自定义元素?

问题描述

我似乎无法在角度组件(自定义元素)中传递 JSON 数组。我有循环遍历 JSON 数组的代码,并且我在@Inject. 例子:

import {
  Input,
  Component,
  ViewEncapsulation,
  EventEmitter,
  Output
} from '@angular/core';

@Component({
  selector: 'custom-wrapper',
  template: `
  <ul>
      <li *ngFor="let item of items
        {{ item.title }}
        {{ item.age }}
      </li>
    </ul>
  `,
  encapsulation: ViewEncapsulation.Native
})
export class WrapperComponent {
  @Input() items: any[];
}

然后,在我的index.html文件中,我调用custom element并尝试将一个 JSON 对象数组传递给它,例如:

<custom-wrapper [items]="[{"title": "Mr", "age" : 23}, {"title": "Ms", "age" : "25"}]"></custom-wrapper>

<custom-wrapper [items]="[{"title": "Mr", "age" : 23}, {"title": "Ms", "age" : "25"}]"></custom-wrapper>当我处于检查模式时,我得到的只是一个空,并且没有列出任何内容。

有人可以帮我找到问题吗?

标签: arraysangular

解决方案


您应该使用单引号传递您的数组,因为您使用双引号作为属性。

所以这应该是你的 index.html:

<custom-wrapper [items]="[{title: 'Mr', age: 23}, {title: 'Ms', age: 25}]"></custom-wrapper>

同样在你是 WrapperComponent 中,li像这样修复你:

<li *ngFor="let item of items">

推荐阅读