Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

javascript - Add a component dynamically to a child element using a directive

Trying to place a component dynamically to a child element, using a directive.

The component (as template):

@Component({
  selector: 'ps-tooltip',
  template: `
    <div class="ps-tooltip">
      <div class="ps-tooltip-content">
        <span>{{content}}</span>
      </div>
    </div>
  `
})
export class TooltipComponent {

  @Input()
  content: string;

}

the directive:

import { TooltipComponent } from './tooltip.component';

@Directive({
  selector: '[ps-tooltip]',
})
export class TooltipDirective implements AfterViewInit {

  @Input('ps-tooltip') content: string;

  private tooltip: ComponentRef<TooltipComponent>;

  constructor(
      private viewContainerRef: ViewContainerRef,
      private resolver: ComponentFactoryResolver,
      private elRef: ElementRef,
      private renderer: Renderer
  ) { }

  ngAfterViewInit() {
    // add trigger class to el
    this.renderer.setElementClass(this.elRef.nativeElement, 'ps-tooltip-trigger', true); // ok

    // factory comp resolver
    let factory = this.resolver.resolveComponentFactory(TooltipComponent);

    // create component
    this.tooltip = this.viewContainerRef.createComponent(factory);
    console.log(this.tooltip);

    // set content of the component
    this.tooltip.instance.content = this.content as string;
  }
}

The problem is that this is creating a sibling and I want a child (see bellow)

result:

<a class="ps-btn ps-tooltip-trigger" ng-reflect-content="the tooltip">
  <span>Button</span>
</a>
<ps-tooltip>...</ps-tooltip>

wanted result:

<a class="ps-btn ps-tooltip-trigger" ng-reflect-content="the tooltip">
  <span>Button</span>
  <ps-tooltip>...</ps-tooltip>
</a>

Thanks in advance for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Even dynamic component is inserted as subling element you can still move element to desired place by using:

this.elRef.nativeElement.appendChild(this.tooltip.location.nativeElement);

Plunker Example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...