2016-09-08 4 views
2

Так что я сейчас пытаюсь создать вложенные комментарии, и в настоящее время я ввожу компонент динамической формы, чтобы люди могли ответить на комментарий. Он работает хорошо, когда есть только родители и дети, но если есть братья и сестры, он выбирает первый. Например,Angular2 Сделать селектор ViewContainerRef динамическим

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

Если я нажимаю на <a> теге 3 внуки, который содержит селектор #replylink формы будет добавляться к первому внуки - как все они имеют #replylink. Есть в любом случае, что я могу сделать этот тег динамический? Как #replylink{{comment.id}}, а затем сможете обновить @viewchild, чтобы иметь возможность его найти?

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

<a> тег:

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

ответ

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) { 
    ... 
    } 
} 
+0

Как будет идти об установке viewContainerRef быть комментарий? –

+0

Извините, я не понимаю вопроса. Было бы проще, если бы вы добавили код на свой вопрос, который демонстрирует, что вы пытаетесь выполнить, что вы пробовали и где вы потерпели неудачу. –

+0

Хорошо, я обновил сообщение. Это с viewContainerRef.createComponent, он всегда будет обращаться к первой ссылке #replylink, поскольку childComments проходят через ngFor для каждого комментария. –

Смежные вопросы