首页 > 解决方案 > 如何使用 ng-content 从另一个组件中获取特定元素

问题描述

我想从 random.component 中获取一个元素,并通过以某种方式选择它来将其显示在我的主要模式组件的页脚中。

random.component.html

<div>random text</div>
<span projectThis>text text</span>

用例.component.html

<modal>
   <random></random>
</modal>

我已经尝试过了,但没有奏效:

modal.component.html

<h5>Title</h5>
<div>Random long text</div>
<ng-content select="[projectThis]"></ng-content>

我也尝试过不同的选择器类型——类名、角色。当我删除选择器时,它会显示整个组件,但选择不起作用。

标签: angular

解决方案


我认为上述方法行不通,因为模态的内容是一个组件,并且将动态构建。

我试过这种方式,看看Stacklitz

基本上,我在模态组件中使用 获得了随机组件引用,@ContentChild在随机组件中获得了对projectThis元素的引用,最后使用renderer

//Modal
<div #footer></div>


@ContentChild(RandomComponent) randomComponent: RandomComponent;
@ViewChild("footer") footer: ElementRef<HTMLElement>;

constructor(public renderer: Renderer2) {}

ngAfterContentInit() {
  setTimeout(x => {
    this.renderer.appendChild(
      this.footer.nativeElement,
      this.randomComponent.projectThis.nativeElement
    );
  });
}

//Random
<span #projectThis>text text</span>

@ViewChild("projectThis") projectThis: ElementRef<HTMLElement>;

从这篇文章中得到了以上想法

注意:这不是最好的解决方案,但它确实有效。


推荐阅读