I'm facing an issue with a component that requires a business object as an Input
. Within the template of this component, I need to conditionally display some content based on the presence of a property that only exists in certain subclasses of the business object.
export class Thing { public foo: string; }
export class SubThing extends Thing { public bar: number; }
// ...
export class MyComponent {
@Input() thing: Thing;
}
<!-- template file -->
{{ thing.foo }}
<div *ngIf="thing?.bar > 10">Conditional content...</div>
In the past, this setup worked fine due to a lack of strict type checking in the templates. However, with the AOT compiler, things have started to break because the compiler can't verify if thing?.bar
is valid when it only recognizes thing
as a Thing
and not a SubThing
.
I've tried using
*ngIf="thing instanceof SubThing && thing?.bar > 10"
, but the issue is that using instanceof
in the template itself is not allowed. Is there an alternative method to check the type of thing
within the template to resolve this error and regain proper type checking? (I resorted to setting my Input
as any
to get the build to work, but I prefer to have type checking in place if possible.)