TransWikia.com

TemplateRef type checking/declaring type

Stack Overflow Asked by Petr Averyanov on September 17, 2020

Lets assume I have component with generic type that displays data list:

interface DataProvider<T> {
  getData(): T[];
}

...
template: '<div *vsFor="let item in dataProvider.getData()">
    <ng-container *ngTemplateOutlet="rowTemplate; context:{item: item}">
    </ng-container>
</div>'
...
class AwesomeList<T> {
  @Input dataProvider: DataProvider<T>;
  @Input rowTemplate: TemplateRef<T>;
}

Some problem appears, when I use it:

<awesome-list [dataProvider]="provider" [rowTemplate]="template"></awesome-list>

<ng-template #template let-object="item">
{{object.name}} // Here, type of object is unclear (?)
</ng-template>

So is any way to defined object/item class here?

P.S. All this work ok, but I want to end with strict types, autocomplete in IDE, etc.

One Answer

According to angular doc, you can achieve this by setting the flags "strictTemplates" and "fullTemplateTypeCheck" to true (see more here : https://angular.io/guide/template-typecheck)

I did a repro on stackblitz, sadly I don't think you see such errors with stackblitz, you could just copy/paste this in local and see if it works for you (https://stackblitz.com/edit/angular-strict-template-example?file=src/app/app.component.html)

Please note this is only angular compilation related, I'm not sure VS Code will give you the autocomplete

EDIT : Bad news I tried locally with the flags set to true but it is not working (to me the doc is confusing because it says "Infers the correct type of components/directives, including generics.") @amakhrov referenced the issue explaining this feature is not ready yet https://github.com/angular/angular/issues/28731

Answered by bmtheo on September 17, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP