gpt4 book ai didi

angular - 在 Angular 的 ContentChildren 中渲染组件

转载 作者:太空狗 更新时间:2023-10-29 18:12:45 25 4
gpt4 key购买 nike

这是我的组件:

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] .

最佳答案

你应该使用这个模式

  1. 创建 TemplateMarker 指令来标记哪个 templates你想作为参数传递(以防止抓取 other templates )。
  2. 使用 @ContentChildren 注入(inject)标记。
  3. 使用 NgTemplateOutlet 在您需要的地方渲染它们.

提示:您可以多次渲染每个模板并且 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com