angular - Angular 8:问题查找通过多个 ng-content 嵌套的组件
问题描述
尝试查找嵌套在子子组件中的组件时,我遇到了这个问题。
我创建了一个我想要实现的示例:
import { Component, OnInit, ContentChildren, ElementRef, QueryList } from '@angular/core';
@Component({
selector: 'app-grand-parent',
template: '<ng-content></ng-content>',
})
export class GrandParentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
@Component({
selector: 'app-parent',
template: '<ng-content></ng-content>',
})
export class ParentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
@Component({
selector: 'app-child',
template: '<ng-content></ng-content>',
})
export class ChildComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
@Component({
selector: 'app-child-profile',
template: '<div>Child Profile</div>',
})
export class ChildProfileComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
@Component({
selector: 'my-app',
template: `
<div>
<app-grand-parent>
<app-parent>
<app-child>
<app-child-profile></app-child-profile>
<app-child-profile></app-child-profile>
<app-child-profile></app-child-profile>
</app-child>
</app-parent>
</app-grand-parent>
</div>`
})
export class AppComponent implements AfterContentInit {
@ContentChildren(ChildProfileComponent) profiles: QueryList<ChildProfileComponent>;
ngAfterContentInit(): void {
console.log(this.profiles);
}
}
以下链接中有一个完整的示例: https ://stackblitz.com/edit/angular-rqh8gm
我不想使用ngProjectAs
,因为我想动态查询元素。
我可以通过其父组件找到该组件。有没有办法将它重新附加到祖父组件?
解决方案
用于获取配置文件组件的对象。您需要在 app-child 组件中查询它
1)您在 Appcomponent 中找到它,但它没有直接投影在其中,因此您将无法找到它
2)您将其投影在 app-child 中,因此这将在 app-child 中可用
3) 示例
在上述情况下,comp3 投影在 comp2 内部而不是 comp1 中。直接投影在这里工作
看一看
https://stackblitz.com/edit/angular-hwv8g7?embed=1&file=src/app/app.component.ts
如果您想要 Appcomponent 中的访问计数,请尝试此操作。为此,您必须经过多个循环
https://stackblitz.com/edit/angular-shh1up?embed=1&file=src/app/app.component.ts
这是我的方法,如果您找到更好的方法,请告诉我
推荐阅读
- centos - Yum 没有为 CentOS 7.7 提供最新的 FreeIPA (4.8.7)
- python - 由于 pandas 库中的融化而没有影响
- deep-learning - 为什么 FairSeq 的 VQ-Wav2Vec 的输出会丢失帧?
- aeron - agrona 中的 OneToManyRingBuffer 实现
- python-3.x - 让 Telegram Bot 回复特定消息
- smpp - SMPP:submit_sm 和 Deliver_sm
- sql - 从我的表 SQL Server 更改我的数据结果
- c++ - C++:在 Stroustrup 的代码上移动分配/复制问题
- scala - 尝试创建 CoordinatedShutdown 辅助函数
- angular - 如何制作 dist klasor,有角度的?