angular - 如何将每个 @ContentChildren 放入使用 *ngFor 生成的单个 div
问题描述
我试图在这里制作一些类似标签的组件,但我有一些问题。
这是我的组件的用法:
<app-ui-tab001-frame>
<app-ui-tab001-item [tabTitle]="'titleA'">contentA</app-ui-tab001-item>
<app-ui-tab001-item [tabTitle]="'titleB'">contentB</app-ui-tab001-item>
</app-ui-tab001-frame>
“app-ui-tab001-frame”的 html 就像:
<ul>
<li *ngFor="let tab of tabArray.toArray()">
<ng-content></ng-content>
</li>
</ui>
<ul>
<li *ngFor="let tab of tabArray.toArray()">
<div>
**I want to put each @ContentChildren here**
**tried {{tab.elemRef.nativeElement.innerHTML}} here but not working**
</div>
</li>
</ui>
“app-ui-tab001-item”的 html 就像:
<div class="tab-pane" *ngIf="isActive">
<ng-content></ng-content>
</div>
“app-ui-tab001-frame”的ts就像:
export class UiTab001FrameComponent implements OnInit,AfterContentInit {
@ContentChildren(UiTab001ItemComponent) tabArray : QueryList<UiTab001ItemComponent>;
constructor() { }
ngOnInit() {
}
_checkWindowWidth(){
}
ngAfterContentInit(){
console.log(this.tabArray.toArray());
}
}
“app-ui-tab001-item”的ts就像:
export class UiTab001ItemComponent implements OnInit {
@Input() isActive :boolean = false;
@Input() tabTitle :string = null;
public elemRef :ElementRef<any>;
constructor(private elem :ElementRef<any>) {
this.elemRef = this.elem;
}
ngOnInit() {
}
}
我想要的是将每个“app-ui-tab001-item”组件放入由 *ngFor 生成的单个 div(可能吗?),但我不知道如何使其工作。
我尝试在“app-ui-tab001-item”组件的 constructor() 函数中使用 elementRef,并将“{{tab.elemRef.nativeElement.innerHTML}} 注入这些 div,但它并没有起到作用我想要。实际上我是 Angular 的新手 :( 只需要有人指出我的错误
解决方案
是的你可以。ng-content
只需将项目包装在其中ng-template
并用于ngTemplateOutlet
在列表组件中呈现项目。
@Component({
selector: 'my-item',
template: `
<ng-template #content>
<ng-content></ng-content>
</ng-template>
`
})
export class ItemComponent {
@ViewChild('content', { static: true }) content: TemplateRef<void>;
}
@Component({
selector: 'my-list',
template: `
<ul>
<li *ngFor="let tab of tabArray">
<div>
<ng-template [ngTemplateOutlet]="tab.content"></ng-template>
</div>
</li>
</ul>
`
})
export class ListComponent {
@ContentChildren(ItemComponent) tabArray : QueryList<ItemComponent>;
}
https://stackblitz.com/edit/angular-nukgpp?file=src%2Fapp%2Fapp.component.ts
推荐阅读
- google-cloud-platform - 需要“compute.firewalls.list”权限
- ios - ARView 中的故障
- c# - C# ASP.NET API - RestSharp
- ckeditor - CKEditor 5 - 帮助在列表中保留样式
- c++ - 火炬 1.6.0 或更高版本的 Pytorch 自定义 CUDA 扩展构建失败
- c# - Microsoft.TeamFoundation 尝试将 AreaPath 与 Team 链接
- r - 来自旧数据帧子集的每 n 行的新数据帧
- java - 使用 tesseract 检测明亮背景上的白色文本
- c++ - 执行 RegGetValueA 时出现错误 87 (INVALID_PARAMETER)
- java - Java Spring - Crud