1

I'm trying to implement key board navigation on a list of components present inside ViewContainerRef, without knowing how many components are actually present.

Current approach: Right now while adding components in ViewContainerRef, I'm storing component index inside view and ComponentRef together as a object in a list i.e:

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

I'm getting index by doing indexOf on ViewContainerRef. For key board navigation , I'm listening to events and traversing through the list I created I above and keeping track of what's currently selected component. Can this be done in a better way?

Fabio_MO
  • 713
  • 1
  • 13
  • 26
javed
  • 33
  • 1
  • 4

1 Answers1

0

ViewContainerRef has the getters length and get ([])

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]);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Doing get on ViewContainerRef would give me a ViewRef, which is useful only if I want to attach or detach it from the view. It won't provide a way to call a function inside selectedComponent. – javed Mar 19 '18 at 16:41
  • I see. In this case I think an approach like shown in https://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 makes this much easier and I think it's more like Angular should be used - less imperative DOM manipulation - more model-driven and the DOM updated by directives. – Günter Zöchbauer Mar 19 '18 at 16:48
  • I'm using similar approach as given in the answer , except that i don't have predefined list of component types. So I pass around ComponentRef instead. – javed Mar 19 '18 at 17:06
  • I guess there is no way around keeping `ComponentRef`s around yourself – Günter Zöchbauer Mar 19 '18 at 18:46