在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5  HTML/ angular4 動(dòng)態(tài)創(chuàng)建組件

angular4 動(dòng)態(tài)創(chuàng)建組件

我想用Directive做一個(gè)公共的指令,當(dāng)鼠標(biāo)點(diǎn)擊目標(biāo)元素時(shí),顯示一個(gè)組件的內(nèi)容,鼠標(biāo)離開消失,
目前我是點(diǎn)擊時(shí)用ViewContainerRef插入組件,
但是插入的組件與目標(biāo)元素并列,而我想插入目標(biāo)元素里面,
比如目標(biāo)元素為<span appTxt><span/>,插入的組件的html為<span>hi<span/>
當(dāng)我點(diǎn)擊時(shí),會(huì)變成<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);

}

}

回答
編輯回答
懶洋洋

可以在指令的宿主元素下加一個(gè)ng-container作為動(dòng)態(tài)組件容器,ng-container會(huì)在渲染時(shí)消失。
指令可以做一些修改:

@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(動(dòng)態(tài)組件);
    this.dyView.createComponent(componentFactory);
  }

}

目標(biāo)元素:

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

目標(biāo)元素所在組件獲取ng-container容器作為參數(shù)傳給指令:

@ViewChild('dy',{read:ViewContainerRef}) dyView:ViewContainerRef
2018年6月14日 23:20