首页 > 解决方案 > 为每个 ng-template 添加标签

问题描述

我正在尝试为我的每个添加标签名称,然后将该标签保存在 a 中,但我不确定如何执行此操作。ng-templateproperty

我想这样做是因为,当迭代 s列表时,我希望每个都ng-template与正确的Label相关联。ng-template

注意: 我正在创建一个可重用的 Tab 组件。Tab 组件将保存逻辑,而 Parent 组件将保存ng-templates,因为只有 Parent 知道它需要什么样的模板。

每个都ng-template需要一个标签标签来搭配它。

尝试过: 我尝试过添加name = "Label 2"ng-template但我认为这没有任何作用。

 <ng-template #temp1 name="Label 2"> <p>this is template 2</p> </ng-template>

目标:我想templates用这样的东西填充我的财产object

let templates = {tempLabel: 'Label 2', template: 'temp1'}

我已经得到了template: temp1部分,我只需要tempLabel: 'Label 2对象的部分。

标签: angularng-template

解决方案


您可以创建将存储标签和模板本身的自定义指令,如下所示:

@Directive({
  selector: '[appLabel]'
})
export class LabelDirective {
  constructor(public templateRef: TemplateRef<any>) { }
  @Input('appLabel') label = '';
}

并将其注入组件:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChildren(LabelDirective) templates: QueryList<LabelDirective> 
}

这是 AppComponent 模板:

<ng-template appLabel="label 1"></ng-template>
<ng-template appLabel="label 2"></ng-template>
<ng-template appLabel="label 3"></ng-template>

<ul>
    <li *ngFor="let t of templates">{{t.label}} - {{ t.templateRef }}</li>
</ul>

这是工作示例https://stackblitz.com/edit/angular-w8sd4y


推荐阅读