3

With the following html:

<div [ngSwitch]="type">
    <my-component-a *ngSwitchCase="'A'"></my-component-a>
    <my-component-b *ngSwitchCase="'B'"></my-component-b>
    <my-component-c *ngSwitchCase="'C'"></my-component-c>
    <my-component-d *ngSwitchDefault></my-component-d>
</div>

How do I get a reference to the chosen component inside the ts code? e.g.

public getChosenComponent(): MyComponentBase {
    return ???;
}
user1589188
  • 5,316
  • 17
  • 67
  • 130

1 Answers1

4

Since you have base class you could use one method that is described in the docs https://angular.io/guide/dependency-injection-in-action#find-a-parent-by-its-class-interface

You need to provide MyComponentBase on all of your components that are supposed to be a chosen component. For example, CompB could be declared as follows:

@Directive({
  selector: 'my-component-b',
  providers: [{ provide: MyComponentBase, useExisting: CompB }]
})
export class CompB {}

Now you need to query chosen component by using @ViewChild decorator:

@ViewChild(MyComponentBase) component: MyComponentBase;

and then you will be able to get choosen component after view has been rendered:

getChosenComponent(): MyComponentBase {
  return this.component;
}

ngAfterViewInit() {
  console.log(this.getChosenComponent());
}

Example

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • Ah cool. I will try that like you said my components in this case all extend from the same base class. Will you be providing a more generic way for components of different classes? Or will @ViewChild still be able to find the component chosen by ngSwitchCase? – user1589188 Jan 23 '18 at 08:36
  • ViewChild will only find those instances that fit the token we specified in ViewChild decorator. See also https://stackoverflow.com/questions/39908967/how-to-get-reference-of-the-component-associated-with-elementref-in-angular-2/39909203#39909203 – yurzui Jan 23 '18 at 09:03