Angular pass a Component as ng-template of another Component
What you can do is this:
When you call component A, you pass an ng-template to that as follows:
<app-component-a> <ng-template *ngIf=”condition; else elseBlock”> <app-component-b></app-component-b> </ng-template> <ng-template #elseBlock> <app-component-c></app-component-c> </ng-template></app-component-a>
Now in your app-component-a.ts you do this:
@ContentChild(TemplateRef) template: TemplateRef;
So basically template will get component b or c based on your condition.
And then in component A template, you do this:
<ng-container [ngTemplateOutlet]="template"></ng-container>
So now your ng-container will get Component B or C based on your condition.
As far as your form is concerned, i'm afraid the only thing I can think of is to create a service and provide it in component A, inject it in A,B and C and share the form in that service.
But if you include component B and C the way I have shown above, Angular will handle creation and destruction of your B and C components on it's own.
Otherwise when your ng-template condition changes, your component B will not be destroyed when component C is instantiated.
Edit:
One more thing I can think of is that if you are not calling component B or C as soon as A is instantiated, you could also emit (@Output) form from A to A's parent oninit of A. This way when B or C is called, A's parent will have access to form and it can pass it to B or C.
Have you tried by simply doing:
<app-component-a #compA [entity]="row" [entityName]="entityName"> <app-component-b [inline]="true" [form]="compA.form" ></app-component-b></app-component-a>// component-a.html<div class="row-detail-panel"> <h4 class="row-detail-panel-title">{{ newEntity ? 'Add new' : 'Edit this'}} {{ entityName }}</h4> <ng-content></ng-content></div>
In order for this to work, the form
member defined in the A component should be public, and preferably readonly
.