0

我想用Directive做一个公共的指令,当鼠标点击目标元素时,显示一个组件的内容,鼠标离开消失,
目前我是点击时用ViewContainerRef插入组件,
但是插入的组件与目标元素并列,而我想插入目标元素里面,
比如目标元素为<span appTxt><span/>,插入的组件的html为<span>hi<span/>
当我点击时,会变成<span appTxt><span/><span>hi<span/>
但wo 想要的效果是<span appTxt><span>hi<span/><span/>
@Directive({
selector: '[appTxt]',
})
export class TxtCopyDirective {

constructor(private el: ElementRef, private renderer2: Renderer2, public viewContainerRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) {

}

@HostListener('click', ['$event']) onclick(event: any) {

this.viewContainerRef.clear();
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(插入的组件);
this.viewContainerRef.createComponent(componentFactory);

}

}

1个回答

0

可以在指令的宿主元素下加一个ng-container作为动态组件容器,ng-container会在渲染时消失。
指令可以做一些修改:

@Directive({
  selector: '[appTxt]'
})
export class TxtCopyDirective {

  @Input('appTxt') dyView:any

  constructor(
    private el: ElementRef, 
    private renderer2: Renderer2, 
    public viewContainerRef: ViewContainerRef, 
    private componentFactoryResolver: ComponentFactoryResolver
  ) {}

  @HostListener('click', ['$event']) onclick(event: any) {
    this.dyView.clear();
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(动态组件);
    this.dyView.createComponent(componentFactory);
  }

}

目标元素:

<span [appTxt]="dyView">
  click
  <ng-container #dy></ng-container>
</span>

目标元素所在组件获取ng-container容器作为参数传给指令:

@ViewChild('dy',{read:ViewContainerRef}) dyView:ViewContainerRef

撰写答案

Planets