我一直在研究这个问题并进行实验,对于如何解决这个问题,或者这是否是预期的行为,我还没有提出一个确凿的答案。
不久前,我遵循了使用componentFactoryResolver (https://v6.angular.io/guide/dynamic-component-loader)创建动态组件的Angular指南。
我遇到的问题是生命周期钩子(ngAfterViewInit、ngOnInit等)在动态创建的组件中,只有将鼠标移到相关组件上才能运行。这似乎是奇怪的行为。
这似乎与更改检测无关,因为手动运行更改检测(this.cdRef.detectChanges())不会触发挂钩。
由于某些原因,我无法创建最小的repro,因为Angular文档中的示例不起作用,所以请参阅下面我的实现的一些片段。除了生命周期钩子之外,一切都很正常。
HTML中的用法:
<div class="modal-body modal-dataFlow animated fadeIn" [hidden]="showNotification">
<ng-template appForms></ng-template>
</div>forms.directive.ts:
import { Directive, ViewContainerRef} from '@angular/core';
@Directive({
selector: '[appForms]'
})
export class FormsDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}form-item.ts:
import { Type } from '@angular/core';
export class FormItem {
constructor(public component: Type<any>, public data: any) { };
}forms.service.ts:
import { Injectable } from '@angular/core';
import { HttpcallerComponent } from '../views/dataflows/forms/httpcaller/httpcaller.component';
import { FormItem } from '../views/dataflows/form-item';
import { Constants } from '../views/dataflows/Constants';
import { Subject } from 'rxjs';
import { Observable } from 'rxjs/internal/Observable';
@Injectable()
export class FormsService {
myBool$: Observable<boolean>;
private boolSubject: Subject<boolean>;
constructor() {
this.boolSubject = new Subject<boolean>();
this.myBool$ = this.boolSubject.asObservable();
}
emitValue(param: boolean) {
this.boolSubject.next(param);
}
getForms() {
return [
new FormItem(HttpcallerComponent, { name: Constants.HTTP_CALLER_ENDPOINT_NAME, stepName: Constants.HTTP_CALLER_STEP_TYPE_NAME })
];
}
}负责加载组件的方法(我将FormItem的一个实例传入此方法):
completeLoad(dataStepInfo, formItem) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(formItem.component);
this.viewContainerRef.clear();
let componentRef = this.viewContainerRef.createComponent(componentFactory);
formItem.data.dataStepInfo = dataStepInfo;
formItem.data.flowId = this.flowID;
(<IForms>componentRef.instance).data = formItem.data;
(<IForms>componentRef.instance).parentForm = this.propertyForm;
this.childComponent = componentRef.instance;
this.componentCreated.next(this.maximiseRegex.test("app." + this.selectedEndpointType + "Step"));
if (dataStepInfo.endpointName === Constants.MERGE_STEP_ENDPOINT_NAME) {
this.dataFlowModal.show();
}
}Httpcaller.component.ts中的生命周期挂钩示例:
import { Component, OnInit, Input, OnDestroy, ChangeDetectorRef, ViewEncapsulation, AfterViewInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormGroupDirective } from '@angular/forms';
import { Observable, Subscription } from 'rxjs';
import { ModalService } from '../../../../services/modal.service';
import { HighlightTag } from 'angular-text-input-highlight';
import { Result } from '../../../../common/result';
@Component({
selector: 'app-httpcaller',
templateUrl: './httpcaller.component.html',
styleUrls: ['./httpcaller.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class HttpcallerComponent implements OnInit, OnDestroy, AfterViewInit {
private confirmed: boolean = false;
private errorText: string;
private sub: Subscription;
private transmission;
public showConfirm: boolean = false;
public alertsDismiss: any = [];
public localHeaders;
private previousContentType;
private formSub: Subscription;
private receivedAuth: number;
private isViewInitialized: boolean = false;
private urlSubscription: Subscription;
@Input() parentForm: FormGroupDirective;
@Input() data: any;
tags: HighlightTag[] = [];
tagClicked: HighlightTag;
httpConfigForm: FormGroup;
private httpConfigSettings = {
httpConfig: null, httpHeaders: null, httpAuthorization: null
}
constructor(
private formBuilder: FormBuilder,
private modalService: ModalService,
private cdRef: ChangeDetectorRef) {
}
public configSelection: string;
public authList: any;
public disableButtons: boolean = false;
private confirmType: boolean = false;
private readonly onPremAgentKey: string = '{{OnPremAgent}}';
ngOnInit() {
if (this.isViewInitialized) {
return;
}
this.isViewInitialized = true;
this.sub = this.modalService.myBool$.subscribe((newBool: boolean) => {
this.confirmed = newBool;
if (this.confirmed && !this.confirmType) {
this.runDeleteAuth();
}
else {
this.checkContentType(this.confirmed);
this.confirmed = false;
}
this.confirmType = false;
});
//this.transmissionId
this.getContentTypes();
this.GetCommonFormatTypes();
this.cdRef.detectChanges();
this.addTags();
}
ngAfterViewInit() {
console.log("AfterViewInit running");
}发布于 2021-04-08 00:42:28
执行此操作可点燃出厂视图:
constructor(private appRef: ApplicationRef) {}在componentRef下面:
this.appRef.attachView(componentRef.hostView);https://stackoverflow.com/questions/60920226
复制相似问题