I have this code
<div>
<wizard-step
[component]="'ExampleComponent'"
></wizard-step>
</div>
ExampleComponent is a component that I want to extract in the component, but when using the component variable, the result is a string in which I want to get the Component object from that name.
Thank you for helping.
CodePudding user response:
If you want to pass the component to the child component as an object reference you could retrieve it in the component using https://angular.io/api/core/ViewChild
@ViewChild(ExampleComponent) exampleComponent: ExampleComponent;
Then in your template you would pass it like this
<div>
<wizard-step [component]="exampleComponent"></wizard-step>
</div>
CodePudding user response:
Two options came to my mind for your issue. Either you create a helper variable or use ng-content
as @dmance suggested.
Option 1 - Helper variable
You need a helper variable because the HTML doesn't have access to the imports, so you need a "proxy" to access the component
TS
exampleComponent: Type<ExampleComponent> = ExampleComponent;
HTML
<div>
<wizard-step [component]="exampleComponent"></wizard-step>
</div>
Option 2 - ng-content
The content projection is helpful, for example, as soon as the content changes in each component and you don't want to add a lot of inputs to your component.
HTML
<div>
<wizard-step>
<example-component></example-component>
</wizard-step>
</div>
But you need to adjust your wizard.component.html
:
<!-- Some HTML -->
...
<div>
<ng-content></ng-content>
<!-- Your component is rendered here => ng-content is the anchor -->
</div>
...
<!-- SOME HTML -->
If you use this option you don't need the @Input
in your Typescript file. For more information see the docs.