1

I would like to use type checking on angular templates.

When a property has 2 or more possible types, the template is not able to determine which is the current type in its context. Even using an "if" to check for the presence of the property, my IDE (VSCODE) isn't happy. With typescript side I could just use if ('property' in myObj) but I can't reproduce this on the template side.

Example: https://stackblitz.com/edit/angular-ivy-bjfyu9?file=src/app/app.component.html

Just remove the FOO interface on the property, then it work...

How can I check the type of a property in an angular template?

I read https://angular.io/guide/template-typecheck but nothing about a case when a property has 2 or more types possibles (except null).

I know it could work if I add a property like "kind" for union in each object. But I can't change the data schema.

Using angular 14

  "angularCompilerOptions": {
    "strictTemplates": true,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true
  }

1 Answer 1

0

If you cannot do anything to the data schema, the last resort would be to use any in the template. Not anything I would ever recommend in any other situation, unless really neccessary, but if there is no other way, then do that:

<div *ngIf="$any(property).date">{{ $any(property).date }}</div>

Your forked STACKBLITZ

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.