1

I'm trying to access a template reference within some nested structural directives:

  <ng-container [ngSwitch]="currentIndex">
      <ng-container *ngFor="let panel of panels; index as panelIndex;">
        <ng-container *ngSwitchCase="panelIndex">
          <ng-container #visiblePanel *ngComponentOutlet="panel; injector: injector"></ng-container>
        </ng-container>
      </ng-container>
  </ng-container>

I try to reference the component with:

  @ViewChild('visiblePanel') currentPanel: WizardPanelComponent;

I've also tried id and Component selectors. Basically, it's always undefined:

  // Button press
  onNext() {
    this.data = this.currentPanel.data;  // this.currentPanel is undefined
    ...
  }

Is there some way to get a reference in ts to the currently switched component?

Anthony
  • 7,638
  • 3
  • 38
  • 71
  • How many panels are visible? – ConnorsFan Oct 10 '18 at 21:08
  • Only one `[ngSwitch]="currentIndex"`. If I remove access to the `@ViewChild` I can cycle through the panels. – Anthony Oct 10 '18 at 21:10
  • Try `@ViewChild(WizardPanelComponent) currentPanel: WizardPanelComponent;`. – ConnorsFan Oct 10 '18 at 21:12
  • you're redefining `#visiblePanel` variable at the each itteration, looks weird – WildDev Oct 10 '18 at 21:14
  • I did try that, I gave it another run for sanity's sake and still undefined. – Anthony Oct 10 '18 at 21:16
  • @WildDev You can `#ref` each switch case since there's only one uncommented at any time. However, even a `WizardPanelComponent` selector yields undefined. – Anthony Oct 10 '18 at 21:17
  • You could try with `@ViewChildren(WizardPanelComponent)`, subscribing to the `QueryList.changes` event. See [this answer](https://stackoverflow.com/a/51730156/1009922). – ConnorsFan Oct 10 '18 at 21:32
  • The change event never emits. It seems the selector just won't line up with the DOM. – Anthony Oct 10 '18 at 21:54
  • @Anthony, seems to be that's expected behavior. It gonna work once it assigned outside the loop. The closest stuff there exists is `panel; injector: injector; content: myContent` third "content" option. Guess, it would be most preferable way to redesign this block – WildDev Oct 12 '18 at 19:16
  • Thanks, my research seemed to demonstrate that references of `componentOutlet `were a no-go. I went back to a `ComponentFactory` implementation. – Anthony Oct 12 '18 at 19:48

1 Answers1

0

First of all you don't need ngSwitch. So change the code as

  <ng-container>
      <ng-container *ngFor="let panel of panels; index as panelIndex;">
        <ng-container *ngIf="panelIndex === currentIndex">
          <ng-container #visiblePanel *ngComponentOutlet="panel; injector: injector"></ng-container>
        </ng-container>
      </ng-container>
  </ng-container>
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
  • That's a good simplification, but it didn't solve the undefined issue. I still can't select the component outlet with ref, or type. – Anthony Oct 10 '18 at 22:08