gpt4 book ai didi

typescript - Angular2 NgFor 在组件内

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:01 24 4
gpt4 key购买 nike

我有一个树状结构,并尝试从 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>

问题

我遇到了一个错误

Can't bind to 'ngForFor' since it isn't a know property of the 'template' element and there are no matching directives with a corresponding property

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

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

谢谢

最佳答案

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

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

*ng-for 更改为 *ngFor

*#item改成let item

关于typescript - Angular2 NgFor 在组件内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32370710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com