所以我目前正在尝试创建嵌套评论,并且我目前正在引入一个动态表单组件,以便人们可以回复评论。当只有 parent 和 child 时,它效果很好,但如果有 sibling ,它会选择第一个。例如,
--[Root Comment]
--[Child Comment]
--[1 - Grandchild]
--[2 - Grandchild]
--[3 - Grandchild]
如果我点击<a>
包含选择器 #replylink
的第三个孙子标记该表格将附加到第一个孙子 - 因为他们都有 #replylink.
无论如何,我可以使这个标签动态化吗?喜欢#replylink{{comment.id}}
然后就可以更新 @viewchild
能够找到它吗?
编辑:
@Component({
moduleId: module.id,
selector: 'commentsLoop',
templateUrl: 'comments.loop.component.html',
entryComponents: [CommentsFormComponent],
directives: [CommentsLoopComponent]
})
export class CommentsLoopComponent implements OnInit {
@Input() childComments:any;
@Input() type:any;
@Input() id:any;
@ViewChild('replylink', {read: ViewContainerRef}) viewContainerRef;
voteSubscription:any;
private componentFactory: ComponentFactory<any>;
constructor(private _http:Http, private _modal:ModalComponent, componentFactoryResolver: ComponentFactoryResolver, compiler: Compiler, private _auth: AuthService){
this.componentFactory = componentFactoryResolver.resolveComponentFactory(CommentsFormComponent);
};
ngOnInit(){};
commentReply(id,generation,child){
let instance = this.viewContainerRef.createComponent(this.componentFactory, 0).instance;
instance.comment_id = id;
if(child) instance.parent_id = child;
instance.id = this.id;
instance.type = this.type;
instance.generation = generation + 1;
}
}
...other stuff...
}
<a>
标签是:
<a (click)="commentReply(comment.comment_id, comment.generation, comment.id)" #replylink>Reply</a>
最佳答案
您无法使模板变量名称动态化。
你能做的就是使用
@ViewChildren('replyLink', {read: ViewContainerRef}) viewContainerRefs:QueryList<ViewContainerRef>;
获取所有这些,然后选择一个标准,例如
commentReply(id,generation,child){
let vcRef = this.viewContainerRefs.toArray().filter(c => c.id == id);
if(comment.length) {
...
}
}
关于Angular2 使 ViewContainerRef 选择器动态化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39384357/