Angular2使ViewContainerRef选择器动态化

时间:2016-09-08 06:52:44

标签: angular angular2-template

因此,我目前正在尝试创建嵌套评论,而且我目前正在引入动态表单组件,以便人们可以回复评论。当只有父母和孩子时,它运作良好,但如果有兄弟姐妹,它会选择第一个。例如,

--[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>

1 个答案:

答案 0 :(得分:3)

您无法使模板变量名称动态化。

你可以做的是使用

@ViewChildren('replyLink', {read: ViewContainerRef}) viewContainerRefs:QueryList<ViewContainerRef>;

获取所有这些内容,然后根据

等标准进行选择
commentReply(id,generation,child){
  let vcRef = this.viewContainerRefs.toArray().filter(c => c.id == id);
  if(comment.length) {
    ...
  }
}