使用@ContentChildren()访问每个模板名称

问题描述 投票:2回答:1

我写了一个名为my-component的组件,并在里面添加了一些ng-template,并用#命名每个:

<my-component>
    <ng-template #one>
        1st format
    </ng-template>
    <ng-template  #two>
        2nd template
    </ng-template>
    <ng-template  #three>
        3rd template
    </ng-template>
</my-component>

MyComponent的声明中,我使用@ContentChildren(TemplateRef)访问这三个模板。

现在我需要以某种方式在one中访问这些模板的名称(twothreeMyComponent

这是代码:sample code

angular angular-directive angular6 ng-template
1个回答
1
投票

我创建了一个使用ng-templates的组件,我很难找到有关它的文档。一些试验和错误,我想出了如何使用@ContentChild

  @ContentChild('one') oneTemplate: TemplateRef<any>;
  @ContentChild('two') twoTemplate: TemplateRef<any>;

然后在my-component的UI html模板中,你可以像这样使用它们:

<ng-container *ngTemplateOutlet="oneTemplate"></ng-container>
<ng-container *ngTemplateOutlet="twoTemplate"></ng-container>

组件使用情况与您描述的类似:

<my-component>
    <ng-template #one>
        1st format
    </ng-template>
    <ng-template  #two>
        2nd template
    </ng-template>
</my-component>

希望这有助于并为某人工作。反馈意见。

© www.soinside.com 2019 - 2024. All rights reserved.