angular - 如何使用 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>
我也尝试过不同的选择器类型——类名、角色。当我删除选择器时,它会显示整个组件,但选择不起作用。
解决方案
我认为上述方法行不通,因为模态的内容是一个组件,并且将动态构建。
我试过这种方式,看看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>;
从这篇文章中得到了以上想法
注意:这不是最好的解决方案,但它确实有效。
推荐阅读
- python - 如何根据用户在运行时选择的逻辑创建新的 pandas 列
- node.js - socket.io 出现错误:“意外的令牌......”
- python - 在for循环中将多个数字相除
- facebook - 使用 facebook 登录返回无效的应用程序 ID
- ibm-mq - IBM MQ-创建远程队列的新本地定义
- java - 哪个依赖自动导入struts依赖
- python - 如何从单个项目 DataFrame 中获取值
- java - 如何添加功能以使每次鼠标单击时圆圈的大小加倍?
- javascript - ESlint 全局安装 mac root 终端报错
- powerbi - 在 Power BI 中从“导入”更改为“直接查询”