I'm using Angular 8 for a project, and I'm having trouble launching a dynamic component because ngOnInit doesn't get called. I've build a directive called PlaceholderDirective, shown below:
@Directive({
selector: '[appPlaceholder]'
})
export class PlaceholderDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
And used that directive on a ng-template:
<ng-template appPlaceholder></ng-template>
The component that holds the HTML where the ng-template lies launches the dynamic component, as such:
@ViewChild(PlaceholderDirective, {static: false}) private placeholder: PlaceholderDirective;
...
constructor(private componentResolver: ComponentFactoryResolver) {}
...
public launchSensorEditComponent(id: number) {
const componentFactory = this.componentResolver.resolveComponentFactory(SensorEditComponent);
const hostViewContainerRef = this.placeholder.viewContainerRef;
hostViewContainerRef.clear();
const sensorEditComponentRef = hostViewContainerRef.createComponent(componentFactory);
sensorEditComponentRef.instance.sensorId = id;
}
The actual dynamic component is very simple, and its registered in the entryComponents section in AppModule. I've narrow it down to the bare minimum in order to understand what's wrong:
@Component({
selector: 'app-sensor-edit',
templateUrl: './sensor-edit.component.html',
styleUrls: ['./sensor-edit.component.css']
})
export class SensorEditComponent implements OnInit {
@Input() sensorId: number;
private showDialog: boolean = false;
constructor() {
console.log('constructor');
}
ngOnInit() {
console.log('ngOnInit');
this.showDialog = true;
}
Last, the HTML for the dynamic component:
<div *ngIf="showDialog">
<h3>its not working</h3>
</div>
The problem is that ngOnInit from the dynamic component doesn't get called and I have the rest of the data to initialize in there, so that I can build the rest of the template.
The really weird part is that if my console is not opened, and I open it or vice-versa, the template is shown.