我遇到了一些问题,所以我先编写代码,然后尝试解释我想要实现的内容,这里是我的类PostComponent:
export class PostComponent implements OnInit {
@Input('data') data;
@Input('comments') comments = [
{
text:"data"
}
]
constructor(){}
ngOnInit(){}
}
这是我的post.component.html:
<div class="data">
<h2>{{data}}</h2>
<ul>
<li *ngFor="let coment of comments">
{{coment.text}}
</li>
</ul>
</div>
这是我的AppComponent.component.ts:
export class AppComponent {
posts = [
{
data:"data1",
comments:[
{
text: 'text1'
},
{
text: 'text2'
}
]
},
{
data:"data2",
comments:[
{
text: 'text3'
},
{
text: 'text5'
}
]
}
constructor(){}
}
那是我的app.component.html:
<div *ngFor="let post of posts" >
// the value of the selector is post instead of app-post
<post [data]="post.data" [comments]="post.comments" >
</post>
</div>
这就是我想要的:
data1
text1
text2
data2
text3
text5
但是我在控制台中收到错误:
ng:///AppModule/PostComponent.ngfactory.js:105 ERROR Error: Cannot find a
differ supporting object '[object Object]' of type 'object'. NgFor only
supports binding to Iterables such as Arrays.
我希望你理解我的问题,非常感谢任何帮助。
答案 0 :(得分:1)
检查组件选择器
@Component({
selector: 'app-post',
})
//如果您正在使用帖子,那么您需要将其更改为
@Component({
selector: 'post',
})
答案 1 :(得分:1)
将你的帖子发送到
posts = [
{
data:"data1",
comments:[
{
text: 'text1'
},
{
text: 'text2'
}
]
},
{
data:"data2",
comments:[
{
text: 'text3'
},
{
text: 'text5'
}
]
}]
<div *ngFor="let post of posts" >
// the value of the selector is post instead of app-post
<post [data]="post.data" [comments]="post.comments" >
</post>
</div>