这是我的组件:
import { Component, OnInit, ContentChildren, QueryList } from '@angular/core';
import { IconBoxComponent } from '../icon-box/icon-box.component';
@Component({
selector: 'app-three-icon-box',
templateUrl: './three-icon-box.component.html',
styleUrls: ['./three-icon-box.component.scss']
})
export class ThreeIconBoxComponent implements OnInit {
@ContentChildren(IconBoxComponent) boxes: QueryList<IconBoxComponent>;
constructor() { }
ngOnInit() {
}
ngAfterContentInit() {
console.log(this.boxes);
}
}
它的模板如下所示:
<div class="row justify-content-center">
<div class="col-12 col-md-10">
<div class="row justify-content-center text-center">
<div *ngFor="let box of boxes" class="col-12 col-sm-4 col-lg-3 offset-lg-1 lz-mb-2 lz-mb-sm-0">
{{ box }}
</div>
</div>
</div>
</div>
这就是我渲染它的方式:
<app-three-icon-box>
<app-icon-box icon="#icon-one">content 1</app-icon-box>
<app-icon-box icon="#icon-two">content 2</app-icon-box>
<app-icon-box icon="#icon-three">content 3</app-icon-box>
</app-three-icon-box>
在第二个代码块中,我试图呈现
<app-icon-box>
,但我不知道如何呈现。 {{ box }}
只是我想要做的事情的一个想法,但我只得到 [object Object]
。 最佳答案
你应该使用这种模式
@ContentChildren
注入(inject)标记。 提示:您可以多次渲染每个模板和 send them parameters 。
例子:
import { Component, Input, Directive, TemplateRef, ContentChildren, QueryList } from '@angular/core';
@Directive({
selector: '[templateMarker]'
})
export class TemplateMarker {
constructor(public template: TemplateRef<any>) {}
}
@Component({
selector: 'template-owner',
template: `
<div *ngFor="let marker of markers">
<i><ng-template [ngTemplateOutlet]="marker.template"></ng-template></i>
</div>
`,
})
export class TemplateOwner {
@ContentChildren(TemplateMarker) markers: QueryList<TemplateMarker>;
}
@Component({
selector: 'hello',
template: `<template-owner>
<div *templateMarker>first template</div>
<div *templateMarker>second template</div>
</template-owner>`,
})
export class HelloComponent {}
关于angular - 在 Angular 的 ContentChildren 中渲染组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49287859/