【发布时间】:2020-01-03 23:40:59
【问题描述】:
我在一个项目中使用 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 没有被调用,我有其余的数据要在那里初始化,这样我就可以构建模板的其余部分。
真正奇怪的是,如果我的控制台没有打开,而我打开它或反之亦然,模板就会显示出来。
【问题讨论】:
-
我设法通过在 viewContainer 上调用 detectChanges() 使其工作
-
用大锤解决问题。
-
我明白了,稍后我会尝试使用您给我的链接,但现在我将使用大锤方法离开。感谢您的帮助!
标签: angular angular-components angular-dynamic-components angular-lifecycle-hooks