【问题标题】:Angular2 NgFor Within ComponentsAngular2 NgFor 在组件内
【发布时间】:2015-11-28 23:57:09
【问题描述】:

我有一个树状结构,并尝试从 angular2 中的组件和子组件创建一个列表。

var data = [
  {id:"1", 
   children: [
     {id:"2", 
      children: [
        {id: "3"},
        {id: "3"},
        {id: "3"},
        {id: "3"},
      ]},
      {id:"2", 
      children: [
        {id: "3"},
        {id: "3"},
        {id: "3"},
        {id: "3"},
      ]}
   ]}
]

我正在尝试遍历该结构并根据循环迭代的深度使用不同的组件构建一个 html 列表。

TypeScript

// ROOT
@Component({
    selector: 'root',
})

@View({
    templateUrl: '
    <childOne *ng-for="#data for list.children" [data]="data"></childOne>
    ',
    directives: [ChildOne, NgFor]
})

class Root{
    list:Array<Object>;
    constructor() {
       this.list = // request to backend
    }
}

// COMPONENT 1
@Component({
    selector: 'childOne',
    properties: ['data']
})

@View({
    templateUrl: '
    {{data.id}}
    <childTwo *ng-for="#childOneData for data.children" [data]="childOneData "></childTwo>
    ',
    directives: [ChildTwo, NgFor]
})

class ChildOne{
}

// COMPONENT 2
@Component({
    selector: 'childTwo',
    properties: ['data']
})

@View({
    templateUrl: '
    {{data.id}}
    <childThree *ng-for="#childTwoData for data.children" [data]="childTwoData"></childTwo>
    ',
    directives: [ChildThree, NgFor]
})

class ChildOne{
    constructor() {
    }
}

// COMPONENT 3
@Component({
    selector: 'childThree',
    properties: ['data']
})

@View({
    templateUrl: '{{data.id}}',
})

class ChildThree{
    constructor() {
    }
}

HTML

<head>
  <body>
    <root></root>
  </body>
</head>

问题

我遇到了一个错误

无法绑定到“ngForFor”,因为它不是“模板”元素的已知属性,并且没有具有相应属性的匹配指令

错误指的是 ChildTwo 组件中的 *ng-for。当我删除 html 标记时,一切正常。

使用 *ng-for 有什么限制吗?还是一些我没有看到的陷阱?

谢谢

【问题讨论】:

标签: typescript angular


【解决方案1】:

您必须在ng-for 指令中使用of 而不是for

<childTwo *ngFor="let childOneData of data.children" [data]="childOneData "></childTwo>

*ng-for 改为 *ngFor

*#item 改为 let item

【讨论】:

  • 谢谢!在 2 个组件中,我使用了“of”,在第三个组件中使用了“for”。该死!
  • 从 angular2 beta *ng-for 更改为 *ngFor。请更新。
  • @PardeepJain 谢谢,Pardeep!
  • 从 beta-17 开始,# 不再使用,应该是 let
猜你喜欢
  • 2017-12-10
  • 2016-11-20
  • 2023-04-01
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多