gpt4 book ai didi

angular - 如何循环使用部分元素以使用 ng-content 进行投影

转载 作者:行者123 更新时间:2023-12-03 22:01:42 25 4
gpt4 key购买 nike

我正在构建一个步进器并且正在使用“transclusion”和 ng-content动态抓取 section stepper 标签中的元素。 stepper.component View 的工作方式如下:

<ng-content select=".one"></ng-content>
<ng-content select=".two"></ng-content>
<ng-content select=".three"></ng-content>

组件用法如下所示:
<stepper>
<section class="one">content here<section>
<section class="two">content here<section>
<section class="three">content here<section>
</stepper>

但是,我想通过自动识别部分元素来使其动态化:
<ng-content *ngFor="let section of sections; index as i;" select="['section:nth-child(' + i + ')']"></ng-content>

我怎样才能:
  • 获取可用于嵌入的节元素的节点列表?
  • 使用 ng-content 的 select逐步瞄准他们?
  • 最佳答案

    我会创建一个指令,如:

    @Directive({
    selector: '[stepper-section]'
    })
    export class StepperSectionDirective {}

    然后添加 stepper-section每个部分的属性:
    <stepper>
    <section stepper-section>content here<section>
    <section stepper-section>content here<section>
    <section stepper-section>content here<section>
    </stepper>

    最后利用 @ContentChildren装饰器来查询所有部分:
    @ContentChildren(StepperSectionDirective) sections: QueryList<StepperSectionDirective>;

    Ng-run Example

    如果你想遍历内容并动态渲染它,你可以用 ng-template 包裹你的 child 。并使用 ngTemplateOutlet在 StepperComponent 中渲染它们的指令:

    html
    <app-stepper>
    <ng-template stepper-section>Content 1</ng-template>
    <ng-template stepper-section>Content 2</ng-template>
    <ng-template stepper-section>Content 3</ng-template>
    </app-stepper>

    stepper-section.directive.ts
    @Directive({
    selector: '[stepper-section]'
    })
    export class StepperSectionDirective {
    hidden = false;

    constructor(public templateRef: TemplateRef<any>) {}
    }

    stepper.component.ts
    @ContentChildren(StepperSectionDirective) sectionDirs: QueryList<StepperSectionDirective>;

    stepper.component.html
    <button *ngFor="let section of sections; index as i;"
    [class.enabled]="activeSection === i" (click)="goTo(i)">
    Step {{ i + 1 }}
    </button>
    <div class="content">
    <ng-container *ngFor="let section of sections">
    <ng-template *ngIf="!section.hidden"
    [ngTemplateOutlet]="section.templateRef"></ng-template>
    </ng-container>
    </div>

    Ng-run Example

    这两种方法的区别在于,在第一种情况下,所有子内容都被渲染,我们只操作 display: none到那些我们想隐藏的步骤。

    在第二种方法中,我们可以更好地控制要渲染的内容,并且在特定时间只渲染一个步骤。

    关于angular - 如何循环使用部分元素以使用 ng-content 进行投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59381158/

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