我在项目中使用Angular 8,但由于无法调用ngOnInit,因此无法启动动态组件。我建立了一个名为PlaceholderDirective的指令,如下所示:
@Directive({
selector: '[appPlaceholder]'
})
export class PlaceholderDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
并在ng-template上使用了该指令:
<ng-template appPlaceholder></ng-template>
包含ng-template所在HTML的组件将启动动态组件,如下所示:
@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;
}
实际的动态组件非常简单,它已在AppModule的entryComponents部分中注册。为了了解问题所在,我将其缩小到最低限度:
@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;
}
最后,动态组件的HTML:
<div *ngIf="showDialog">
<h3>its not working</h3>
</div>
问题在于动态组件中的ngOnInit不会被调用,并且我有其余数据要在那里初始化,以便我可以构建其余模板。
真正奇怪的是,如果我的控制台没有打开,而我打开了控制台,反之亦然,则显示模板。