angular - 为每个 ng-template 添加标签
问题描述
我正在尝试为我的每个添加标签或名称,然后将该标签保存在 a 中,但我不确定如何执行此操作。ng-template
property
我想这样做是因为,当迭代 s列表时,我希望每个都ng-template
与正确的Label相关联。ng-template
注意:
我正在创建一个可重用的 Tab 组件。Tab 组件将保存逻辑,而 Parent 组件将保存ng-template
s,因为只有 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
对象的部分。
解决方案
您可以创建将存储标签和模板本身的自定义指令,如下所示:
@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>
推荐阅读
- ios - 从导航控制器到选项卡控制器视图
- solr - Solr 查询:如果 field=value1 存在则返回,否则返回 field=value2
- javascript - 基础 XY 网格
- rx-java - RxJava:将重试与扩展的单个 Observable 一起使用不会发出数据
- wordpress - 使用 My Custom Functions 插件编辑我的 wordpress 网站的页脚版权信用后,我的网站已关闭
- java - 命名应用程序包是否有任何严格的规则
- bootstrap-4 - Angular Material TextArea 自动调整大小不适用于 bootstrap 4
- java - 是否需要在本地安装mysql才能在另一台计算机上保存和检索sql数据?
- c++ - C++中的嵌套结构
- jenkins - 如何在电子邮件中使用 Jenkins 发送最新附件?