【问题标题】:Add a component dynamically to a child element using a directive使用指令将组件动态添加到子元素
【发布时间】:2017-07-24 16:51:10
【问题描述】:

尝试使用指令将组件动态放置到子元素。

组件(作为模板):

@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;

}

指令:

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;
  }
}

问题是这是在创建一个兄弟姐妹,我想要一个孩子(见下文)

结果:

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

想要的结果:

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

提前感谢您的帮助!

【问题讨论】:

  • 没有办法做到这一点。您需要一个子组件的ViewContainerRef,其中添加的组件可以是其兄弟姐妹。这就是ViewContainerRef.createComponent() 的工作原理。
  • 感谢您的回答。我能问一下你建议什么来得到想要的结果吗?!

标签: javascript angular typescript components angular2-directives


【解决方案1】:

即使动态组件作为子元素插入,您仍然可以使用以下方法将元素移动到所需位置:

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

Plunker Example

【讨论】:

  • 你绝对的英雄!
【解决方案2】:

更好的方法是在其上使用带有模板引用变量的嵌套ng-template,以便将组件作为兄弟添加到ng-template,但现在是ng-template 的父级的子级。

你的模板应该是

<div class="ps-tooltip">
  <div class="ps-tooltip-content">
    <span>{{content}}</span>
    <ng-template #addHere></ng-template>
  </div>
</div>

在你的组件中

@ViewChild('addHere') addHere: ViewContainerRef;

ngAfterViewInit() {
    ...

    this.tooltip = addHere.createComponent(factory)

    ...
}

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 2016-12-16
    • 2023-03-24
    • 1970-01-01
    • 2016-02-09
    • 2014-09-10
    • 1970-01-01
    • 2013-08-04
    相关资源
    最近更新 更多