【问题标题】:Angular 6 lifecycle hooks not running on dynamically created componentsAngular 6 生命周期钩子不在动态创建的组件上运行
【发布时间】:2020-07-10 05:06:00
【问题描述】:

我一直在研究这个问题并进行试验,但我无法就如何解决这个问题或它是否是预期的行为提出一个结论性的答案。

前段时间,我按照 Angular 指南使用 componentFactoryResolver (https://v6.angular.io/guide/dynamic-component-loader) 创建动态组件。

我遇到的问题是动态创建的组件中的生命周期挂钩(ngAfterViewInit、ngOnInit 等)在鼠标移到相关组件上之前不会运行。这似乎是一种奇怪的行为。

这似乎与更改检测无关,因为手动运行更改检测 (this.cdRef.detectChanges()) 不会触发挂钩。

由于某种原因,Angular 文档中的示例不起作用,我无法创建最小复制,因此请在下面查看我的实现的一些 sn-ps。一切正常,除了生命周期钩子。

在 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");
  }

【问题讨论】:

  • 我没有看到任何生命周期事件!
  • 生命周期钩子在哪里?
  • 这与动态生成的组件中的生命周期挂钩有关。道歉 - 我已经编辑了这个问题以包含一个例子。在这种情况下,直到鼠标移动,ngOnInit 和 ngAfterViewInit 才会被调用。
  • 您发现问题所在了吗?我认为我面临同样的问题

标签: javascript angular typescript


【解决方案1】:

这样做可以点燃工厂视图:

constructor(private appRef: ApplicationRef) {}

以及下面的componentRef:

this.appRef.attachView(componentRef.hostView);

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 2017-03-29
    • 2020-03-15
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2020-09-20
    相关资源
    最近更新 更多