在我的新div内部而不是外部创建的角度指令载荷分量

3g网络火车

我有各种工具提示,因此我决定使用来加载它们directive它工作正常。但问题是它没有加载到主机内部或未附加div没有加载component创建的子div,我发现没有用。

有人可以帮助我吗?

这是我的指令:

import { DOCUMENT } from '@angular/common';
import {
  Directive,
  ElementRef,
  Input,
  OnInit,
  SimpleChanges,
  HostListener,
  ViewContainerRef,
  Renderer2,
  Inject,
  ViewChild,
  ComponentFactoryResolver,
} from '@angular/core';
import { ComponentLoaderService } from './component-loader.service';

export interface LoaderConfig {
  componentName: string;
  action: string;
}
@Directive({
  selector: '[appComponentLoader]',
})
export class ComponentLoaderDirective implements OnInit {
  @Input() loaderConfig: LoaderConfig;

  private _loaderActive = false;

  @ViewChild('container', { read: ViewContainerRef })
  viewContainerRef: ViewContainerRef;

  constructor(
    private componentLoader: ComponentLoaderService,
    private elementRef: ElementRef,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document,
    private vr: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) {}

  ngOnInit() {
    // this.loaderConfig.action = 'mouseenter'
    let child = document.createElement('div');
    child.style.border = '1px solid red';
    this.renderer.appendChild(this.elementRef.nativeElement, child); //my child should hold component
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('recived component name:', this.loaderConfig.action);

    // this.embedComponent();
  }
  @HostListener('mouseenter') mouseover() {
    if (this.loaderConfig.action === 'mouseenter') {
      this.embedComponent();
    } else {
      return;
    }
  }

  @HostListener('mouseleave') mouseleave() {
    if (this.loaderConfig.action === 'mouseenter') {
      this.removeComponent();
    } else return;
  }

  @HostListener('click') onClick() {
    if (this.loaderConfig.action === 'click') {
      this.toggleLoader();
    } else {
      return;
    }
  }

  embedComponent() {
    const componentRef = this.componentLoader.loadComponent(
      this.loaderConfig.componentName
    );
    if (componentRef) {
      this.vr.clear();
      this.vr.createComponent(componentRef); //just appending outside somewhere
    }
  }

  removeComponent() {
    this.vr.detach();
  }

  toggleLoader() {
    this._loaderActive = !this._loaderActive;
    if (this._loaderActive) {
      this.embedComponent();
    } else {
      this.removeComponent();
    }
  }
}

如何在创建的子对象中加载组件?提前致谢

yurzui

您可以简单地将动态渲染的组件的host元素移动到指令的host中。

this.vr.clear();
const ref = this.vr.createComponent(componentRef); //just appending outside somewhere
this.renderer.appendChild(this.elementRef.nativeElement, ref.location.nativeElement);

Ng运行示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章