Angular 12:
I'm trying to insert a variable array of components. with a similar code to the one on the guid:
html
<ng-container *ngFor="let buttons of buttonArray">
<ng-template appHeaderComponent></ng-template>
</ng-container>
ts
@Input('buttons')
buttonArray: Array<HeaderSubComponentHolder>;
@ViewChildren(HeaderComponentDirective)
headerComponents: QueryList<any>;
ngAfterViewInit(): void {
this.loadButtons();
}
loadButtons() {
for (let i = 0; i < this.headerComponents.length; i++) {
const headComponent = this.headerComponents.get(i);
const button: HeaderSubComponentHolder = this.buttonArray[i];
const viewContainerRef: ViewContainerRef = headComponent.viewContainerRef;
const factory = this.componentFactoryResolver.resolveComponentFactory(
button.type
);
viewContainerRef.clear();
const componentRef =
viewContainerRef.createComponent<HeaderSubComponent>(factory);
componentRef.instance.data = button.data;
}
}
But i'm getting an NG0100 error, the first time accessing the page, the buttons appear as normal. But if i go back with a back arrow, the buttons don't appear (I get an undefined error in "this.headerComponents")
Any tip about how to deal with this?
EDIT: Think i found the solution, if i understood the problem is that the sub component bindings were changed during the "After view init" cycle of the component that contains them. I added this at the end
componentRef.changeDetectorRef.detectChanges();