Programmatically get template content

  Kiến thức lập trình

I have a custom angular list component. The list displays the items using an injected (as a child) template:

@ContentChild(TemplateRef) itemTemplate: TemplateRef<any>;

It’s used like this:

<ng-container *ngIf="itemTemplate; else defaultTemplate" [ngTemplateOutlet]="itemTemplate" [ngTemplateOutletContext]="{$implicit: item}"></ng-container>
<ng-template #defaultTemplate>{{item}}</ng-template>

Now the custom component also has a text field for filtering. But since the items are displayed using a template the text could contain anything, since the list supports any generic item type.

I can’t just pass the property name on which I want to filter since the text could display multiple properties for example user first and last name and this using parent component could add any additional text.

What I would prefer not to do:

  • inject filter logic as callback.
  • create a hidden div to add the items to, to display the processed template items and then read out the innerText
  • read out the generated html child elements (would not work properly after the first filter since filtered items are lost forever)

Is it possible to programmatically get the template text of every item while filtering so that I can filter on the innerText of the generated content of the template

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT