我有一个将业务对象作为输入的组件。在此组件的模板中,我想通过检查仅在业务对象的某些子类上存在的属性的值来有条件地呈现某些内容。
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>
这曾经按书面方式工作,因为编译器对模板中的类型检查不是很严格。最近,这开始与AOT编译器发生冲突(不确定确切的时间),因为严格来说,thing?.bar
当编译器认为thing
只是a时,它是无效的Thing
,并且不能肯定地说它是a SubThing
。
我想说些类似的内容,*ngIf="thing instanceof SubThing && thing?.bar > 10"
但不能instanceof
在模板本身中使用。还有其他方法可以检查thing
模板的类型,以便编译器停止抱怨吗?(我通过指定Input为使构建再次正常工作,any
但是如果可能的话,我当然想让我的类型检查回来。)
显然,编译器遵守用户定义类型防护。我只需要在我的组件中定义一个方法:
export class MyComponent {
// ...
/** @internal */ isSubThing(t: Thing): t is SubThing {
return t instanceof SubThing;
}
}
<!-- template file -->
{{ thing.foo }}
<div *ngIf="isSubThing(thing) && thing?.bar > 10">
Conditional content...
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句