在 Angular 6/7 中,我有一个组件,我将内容投影到其中(ParentComponent 模板):
<my-component [templateNames]="['t1', 't2']">
<ng-template name="t1">...</ng-template>
<ng-template name="t2">...</ng-template>
<ng-template>...</ng-template> <!-- not included in [templateNames] -->
</my-component>
在
MyComponent
类,我可以使用 ContentChildren 装饰器获取所有模板的 QueryList:@ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;
挑战在于我想在由 ParentComponent 通过
@Input() templateNames
设置的特定模板上执行代码。 .processTemplates() {
for (const name of this.templateNames) {
const templateRef = this.getTemplateByName(name);
this.doWork(templateRef);
}
}
getTemplateByName(name) {
const templates = this.templates.toArray();
return templates.find(t => ?); // what can I query to distinguish templates?
}
问题是我不知道如何阅读
name
属性或我在 ParentComponent 的 ng-template 标签上设置的任何其他内容。我不知道如何区分一个 TemplateRef 和另一个;请记住,MyComponent 不能对将使用什么名称或是否应该处理所有 ng-templates 做出任何假设——我上面示例中的最后一个不应被处理,因为它没有在 @Input() 模板名称中列出。我可以在 ParentComponent 中设置什么来帮助我区分这两个 TemplateRef 吗?
最佳答案
您可以使用名称输入参数创建指令:
@Directive({
selector: '[template-name]'
})
export class TableColumnDirective {
constructor(public readonly template: TemplateRef<any>) { }
@Input('template-name') columnName: string;
}
使用这种方式: <my-component>
<ng-template template-name="t1">...</ng-template>
<ng-template template-name="t2">...</ng-template>
...
然后在 my-component
以这种方式注入(inject):@ContentChildren(TableColumnDirective) templates: QueryList<TableColumnDirective>;
有关更详细的解释/示例,请查看已接受的答案 from this question
关于angular - 从 QueryList 中识别特定的 Angular TemplateRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52903851/