【问题标题】:projectableNodes in directive using IVY - Failed to execute 'insertBefore' on 'Node'使用 IVY 的指令中的 projectableNodes - 无法在“节点”上执行“插入之前”
【发布时间】:2021-03-28 23:16:38
【问题描述】:

该代码有什么问题:

  @Directive({
  selector: '[appDir]'
})
export class DirDirective {

  constructor(
    private vcr: ViewContainerRef,
    private compFactoryResolver: ComponentFactoryResolver
  ) {}
  ngAfterViewInit() {
    const compAFactory = this.compFactoryResolver.resolveComponentFactory(
      CompAComponent
    );
    const compBFactory = this.compFactoryResolver.resolveComponentFactory(
      CompBComponent
    );

    const compARef = this.vcr.createComponent(compAFactory);

    this.vcr.createComponent(compBFactory, 0, undefined, [
      [compARef.location.nativeElement]
    ]);
  }
}

仅在启用 IVY 时失败

https://stackblitz.com/edit/angular-h3wqc4?file=src%2Fapp%2Fdir.directive.ts

【问题讨论】:

  • 最终目标是什么?
  • 我想使用指令而不是组件。如代码所示,该指令应(动态)创建 2 个组件,并使用 projectableNodes 将其中一个组件插入另一个组件

标签: angular angular-directive ivy angular-dynamic-components


【解决方案1】:

我遇到了这个问题,我就是这样解决的:

第一个 - 将注入器(来自@angular/core)添加到构造函数

constructor(private vcr: ViewContainerRef,
private compFactoryResolver: ComponentFactoryResolver,
private injector: Injector) {}

2nd - 替换这行代码

const compARef = this.vcr.createComponent(compAFactory);

使用以下代码

const compARef = compAFactory.create(this.injector);

顺便说一句:在我的项目中,构造函数上没有 ViewContainerRef,它是用 ViewChild 分配的

@ViewChild('target', { read: ViewContainerRef })
    private vcr: ViewContainerRef;
<ng-container #target></ng-container>

所以如果你有任何问题,你可以试试。

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 2023-04-01
    • 2021-07-30
    • 2014-06-17
    • 2021-02-19
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多