Angular2 使 ViewContainerRef 选择器动态化

标签 angular angular2-template

所以我目前正在尝试创建嵌套评论,并且我目前正在引入一个动态表单组件,以便人们可以回复评论。当只有 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/

相关文章:

angular - Ionic 4 路由器以编程方式销毁页面

angular - 如何在ionic2中执行只读或禁用?

angular - 将 NavigationExtras 传递给模板中的 routerLink

angular - 如何在 ngFor 中引用控件?

javascript - Angular2 View 不更新从共享服务更改的数据

angular - 可观察的行为主体服务 - 单例和提供者

html - 为什么即使导入依赖项后 mat-form-field 也不起作用?

Angular 9 取消订阅 NavigationEnd

typescript - 将 FormGroup 映射到界面对象

html - 如何在angular2中加载图像