I'm working with a dynamic content, and I am using ngTemplateOutlet
with custom directive to create it, but now I need to access the created content elements. I wasn't able to find any relatable answers regarding my problem in a wast list of similar questions.
My current setup (I will omit unnecessary parts to make the example as clear as possible)
The content host component:
(grid.host.component.ts)
@ContentChildren(VvsGridInputCellDirective, { descendants: false }) public inputCols: QueryList<VvsGridInputCellDirective<T>>;
public getTemplateElement(): HTMLElement {
// checks for undefined and null
return this.inputCols.first().templateRef.elementRef;
}
the significant part of the host component template:
(host.template.html)
<td *ngFor="let col of visibleColumns" [class.resized-col]="col?.width > 0">
<div class="cell-height-wrapper" [style.width]="col?.width > 0 ? col.width+'mm':'auto'">
<ng-template [ngTemplateOutlet]="col.templateRef" [ngTemplateOutletContext]="{$implicit: data}" ></ng-template>
</div>
</td>
this.getTemplateElement()
returns the elementRef
of ng-template
itself (which is just some comments), well because the ng-template
does not exist in DOM.
I need to get the contents of that ng-template
directive, but I don't know how;
This is the directive that passes the template for the ngTemplateOutlet
:
(host.cell.directive.ts)
@Directive({
selector: "ng-template[appVvsGridInputCell]",
exportAs: "appVvsGridInputCell"
})
export class VvsGridInputCellDirective<T> {
public definition: ColumnDefinition<T>;
public model: T;
constructor(public templateRef: TemplateRef<any>) {
this.definition = new ColumnDefinition();
}
And finally the usage of the directive. This is a content I want to access:
(uses.all.above.component.template.html)
<ng-template appVvsGridInputCell #cell="appVvsGridInputCell" let-data header="COMMENT">
<div class="no-padding">
<input class="form-control" type="text" [(ngModel)]="data.comment">
</div>
</ng-template>
So that is all there is to it (besides a lot of clutter). Please let me know how can I access the element that was defined in the ng-template appVvsGridInputCell
, because I want to control it within the host.component
. Also leave a note if you need any clarification.
I looked through a lot of questions, but those are ones that i didn't close:
- angular templateRef nativeElement is an empty comment instead of original element
- How do I find Element inside TemplateRef
Stackblitz
I created a proof of concept stackblitz project that replicates my problem: https://stackblitz.com/edit/angular-nx8gyx