Declarative approach
You can use ngComponentOutlet
.
Code:
shapes: ShapeComponent[] = [CircleComponent, SquareComponent];
template:
<ng-container *ngFor="let shape of shapes">
<ng-container *ngComponentOutlet="shape">
</ng-container>
</ng-container>
ngComponentOutlet - Instantiates a single Component type and inserts
its Host View into current View. NgComponentOutlet provides a
declarative approach for dynamic component creation.
NgComponentOutlet requires a component type, if a falsy value is set
the view will clear and any existing component will get destroyed.
So, no hard code needed in template. *ngFor will iterate over component types array in your code
Update
Don't remember add dynamic rendering component to entryComponents
of AppModule:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent, AComponent, BComponent ],
entryComponents: [
AComponent, BComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
StackBlitz Demo
Imperative approach with setting data
app-component.template:
<ng-container #comps>
</ng-container>
Get access to #comps
(ng-container) view by ViewChild
decorator and create components.
So you can't initilize component like b = new BComponent()
.
- First need to resolve component factory.
- Initialize component via viewContainerRef's createComponent method. It returns reference to instantiated component
- By the reference, get access to instance property and update any data as you need
app-component.ts:
@ViewChild('comps', { read: ViewContainerRef }) comps: ViewContainerRef;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
this.comps.clear();
let aComponentFactory = this.componentFactoryResolver.resolveComponentFactory(this.compArr[0]);
let aComponentRef = this.comps.createComponent(aComponentFactory);
(<AComponent>aComponentRef.instance).name = 'A name';
let bComponentFactory = this.componentFactoryResolver.resolveComponentFactory(this.compArr[1]);
let bComponentRef = this.comps.createComponent(bComponentFactory);
(<BComponent>bComponentRef.instance).name = 'B name';
}
StackBlitzh Demo