*ngFor in Angular2
好的,我在 boot.ts 中启动了一项服务,除了设法使我的模板正常工作之外,一切都运行良好。我很抱歉无法用 HTML / Angular 术语表达自己,但我相信我的问题相当明显。
我的简化 *ngFor 循环目前看起来像这样。
1 | {{comment.body}} |
这正如预期的那样输出如下内容
1 2 3 4 | First comment <!-- 1st comment_div closed --> Second comment <!-- 2nd comment_div closed --> ..... Last comment <!-- last comment_div closed |
我想要的是以下
1 2 3 4 | First comment Second comment ..... Last comment ..... <!-- All divs closing here--> |
试试这样的:
在typescript中:
1 2 3 4 5 6 7 8 9 | @Component({ selector: 'comment', template:"<comment [comment]="comment" *ngFor="let comment of comments"> </comment> {{comment?.body}}", directives: [CommentComponent] }) export class CommentComponent { @Input() private comment : Comment; private comments : Array<Comment>; } |
评论类
1 2 3 | export class Comment { public comments : Array<Comment>; } |
这个想法是使用angular模板生成来生成你的树,直到没有更多的级别。
这是一个工作版本,只需将您的评论数组传递给该指令:
https://plnkr.co/edit/SbLJ3eEHU4BKGOPiXioZ?p=preview
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import {Component, Input, OnInit} from '@angular/core'; import {NgFor} from '@angular/common'; @Component({ selector: 'my-comment', providers: [], template: ` 0"> {{subcomments[0] }} <my-comment [subcomments]="subcomments ? subcomments.slice(1): null"></my-comment> `, directives: [NgFor, MyComment] }) export class MyComment implements OnInit { @Input() subcomments: Array<String>; ngOnInit(): void { console.log( this.subcomments.slice(1)); } } |
这就是你使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //our root app component import {Component} from '@angular/core'; import {NgFor} from '@angular/common'; import {MyComment} from 'src/myComment'; @Component({ selector: 'my-app', providers: [], template: ` <h2 *ngFor="let i of items; let k =index">Hello {{name+k}} <my-comment [subcomments]="items"></my-comment> `, directives: [NgFor,MyComment] }) export class App { items : [] = ['ha', 'da', 'fdd']; constructor() { this.name = 'Angular2 (Release Candidate!)' } } |
好的。因此,通过修补以前的答案,我设法完成了它,尽管它显然浪费了 CPU 周期,而且我不知道它是否会产生可能不是静态的数据的问题。
1st) ngFor 应该更类似于经典的 for 循环:for(var i=0; i
无论如何
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | comment.ts import { Component, OnInit, Input} from '@angular/core'; import {MyService} from 'somewhere'; import {MessagePost} from 'somewhere else'; @Component({ moduleId: module.id, selector: 'comment', templateUrl: 'comment.html', directives: [CommentComponent], //This is important! }) export class CommentComponent implements OnInit { @Input() subcomments: Array<MessagePost>; @Input() iterator: number =0; constructor(private _myService: MyService) { } ngOnInit() { if(!subcomments){this.subcomments = this._myService.getMessage();} } } comment.html (template) 0 && subcomments.length -1 >iterator"> {{subcomments[iterator].body}} <comment [subcomments]="subcomments" [iterator]="iterator + 1"> </comment> |