Angular2 使 ViewContainerRef 选择器动态化

Jac*_*ock 2 angular2-template angular

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

--[Root Comment]
    --[Child Comment]
        --[1 - Grandchild]
        --[2 - Grandchild]
        --[3 - Grandchild]
Run Code Online (Sandbox Code Playgroud)

如果我点击<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...
}
Run Code Online (Sandbox Code Playgroud)

<a>标签是:

<a (click)="commentReply(comment.comment_id, comment.generation, comment.id)" #replylink>Reply</a>

Gün*_*uer 5

您不能使模板变量名称动态化。

你可以做的是使用

@ViewChildren('replyLink', {read: ViewContainerRef}) viewContainerRefs:QueryList<ViewContainerRef>;
Run Code Online (Sandbox Code Playgroud)

获得所有这些,然后选择一个标准,如

commentReply(id,generation,child){
  let vcRef = this.viewContainerRefs.toArray().filter(c => c.id == id);
  if(comment.length) {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)