После некоторого возни внутри ngAfterViewInit
, я начал работать так, как я хочу.Это немного уродливо, потому что мне нужно использовать setTimeout
и мне нужно поиграть с внутренними переменными (не уверен, что это хорошая идея) ...
Вот stackblitz демонстрация динамического выбора шаблона и рендеринг по значению переменной.
В двух словах, вот как я это сделал, вам нужно 3 вещи:
// to grab all the templates
@ViewChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;
// to be use for template selection
templateMap: { [key: string]: TemplateRef<any> } = {};
// to avoid rendering during the first run when templateMap is not yet ready
templateMapReady = false;
Затем в ngAfterViewInit
вы делаете следующее, чтобы построить templateMap
:
ngAfterViewInit(): void {
// setTimeout to bypass the ExpressionChangedAfterItHasBeenCheckedError
setTimeout(() => {
// loop through the fetched template
this.templates.toArray().forEach(t => {
// for those ng-template that has a #name, they will have references
const keys = Object.keys((t as any)._def.references);
if (keys.length === 1) {
// so we put these in the templateMap
this.templateMap[keys[0]] = t;
}
});
// now we change it to ready, so it would render it
this.templateMapReady = true;
});
}