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 ???;
}

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
ViewChild will only find those instances that fit the token we specified in ViewChild decorator. See also stackoverflow.com/questions/39908967/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.