Jack Rothrock
Jack Rothrock

Reputation: 427

Angular2 Make the ViewContainerRef selector dynamic

So I'm currently trying to create nested comments, and I'm currently bringing in a dynamic form component so people can respond to the comment. It works well when there are only parents and children, but if there are siblings, it picks the first one. For example,

--[Root Comment]
    --[Child Comment]
        --[1 - Grandchild]
        --[2 - Grandchild]
        --[3 - Grandchild]

If I click on the <a> tag for the 3rd grandchild that contains the selector #replylink the form will be appended to the first grandchild - as they all have #replylink. Is there anyway that I can make this tag dynamic? Like #replylink{{comment.id}} and then be able to update the @viewchild to be able to find it?

EDIT:

@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...
}

the <a> tag is:

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

Upvotes: 2

Views: 1720

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657731

You can't make template variable names dynamic.

What you can do is to use

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

to get all of them and then select on a criteria like

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

Upvotes: 5

Related Questions