4

我写了一个组件命名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, two, ),但我不知道如何。这是代码:示例代码threeMyComponent

4

1 回答 1

5

我创建了一个使用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>

希望这对某人有所帮助和工作。反馈表示赞赏。

于 2019-03-06T15:24:08.293 回答