Fletch
Fletch

Reputation: 907

Dynamically change displayed angular child component

I have a parent component in which I have set up an array of child components (each extending BaseChild). I use an *ngFor to loop through the children and display their name. I would like to click on the name of the child and insert the html of the child into the parent. However I don't want to hardcode a lot of *ngIf={{child1ShouldBeDisplayed}} in the parent html - there will be a lot of children and things will get very ugly.

I've tried using ng-content as suggested here but it seems that this is for injecting parent html into the child (from here). I've read through a description of ng-template, ng-container etc here but it doesn't seem to meet my needs.

Here is a StackBlitz which sets up the basic code. I'm not sure how to continue. Is there a way to choose which child to display in the parent without the use of loads of *ngIf statements?

Upvotes: 0

Views: 1869

Answers (1)

Marcell Kiss
Marcell Kiss

Reputation: 556

There is a great tutorial for this on the official Angular site, with a stackblitz example.

Summary

You need to create a directive. You'll apply your components dynamically through this directive:

@Directive({
  selector: '[dynamic-stuff]',
})
export class DynamicStuffDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

You need a reference to this element (<ng-emplate dynamic-stuff></ng-template>):

@ViewChild(DynamicStuffDirective, {static: true}) dynamicStuff: DynamicStuffDirective;

You have to create a component factory for your component:

const componentFactory =
  this.componentFactoryResolver.resolveComponentFactory(selectedComponent);

You have to apply it through the viewContainerRef of the directive:

this.dynamicStuff.viewContainerRef.clear();
this.dynamicStuff.viewContainerRef.createComponent(componentFactory);

Good luck, I hope I could help.

Upvotes: 1

Related Questions