【问题标题】:How to traverse through list of components inside ViewContainerRef?如何遍历 ViewContainerRef 中的组件列表?
【发布时间】:2018-08-28 05:58:49
【问题描述】:

我正在尝试在 ViewContainerRef 中存在的组件列表上实现键盘导航,但不知道实际存在多少组件。

当前方法:现在在 ViewContainerRef 中添加组件时,我将组件索引存储在视图中,并将 ComponentRef 作为对象一起存储在列表中,即:

{ component : ComponentRef<any>, index: number }

我通过在ViewContainerRef 上执行indexOf 来获取索引。 对于键盘导航,我正在监听事件并遍历我在上面创建的列表并跟踪当前选择的组件。 能否以更好的方式做到这一点?

【问题讨论】:

    标签: javascript angular angular5


    【解决方案1】:

    ViewContainerRef 具有吸气剂 lengthget ([])

    selectedIndex:number = 0;
    
    cursorUp() {
      if(this.selectedIndex > 0) {
        this.selectedIndex--;
      }
      console.log('selectedComponent', this.vcRef[this.selectedIndex]);
    }
    
    cursorDown() {
      if(this.selectedIndex < this.vcRef.length - 1) {
        this.selectedIndex++;
      }
      console.log('selectedComponent', this.vcRef[this.selectedIndex]);
    }
    

    【讨论】:

    • 打开 ViewContainerRef 会给我一个 ViewRef,仅当我想从视图中附加或分离它时才有用。它不会提供在 selectedComponent 中调用函数的方法。
    • 我明白了。在这种情况下,我认为stackoverflow.com/questions/36325212/… 中所示的方法使这更容易,我认为它更像是应该使用 Angular - 更少的命令式 DOM 操作 - 更多的模型驱动和指令更新的 DOM。
    • 我正在使用与答案中给出的类似方法,除了我没有预定义的组件类型列表。所以我改为传递 ComponentRef。
    • 我想没有办法让ComponentRefs 留在自己身边
    猜你喜欢
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多