我有一个将业务对象作为输入的组件。在此组件的模板中,我想通过检查仅存在于业务对象的某些子类上的属性值来有条件地呈现某些内容。
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
只是一个 时,
,并且不能确定它是 thing?.bar
是无效的>ThingSubThing
。
我想说类似 *ngIf="thing instanceof SubThing && thing?.bar > 10"
但我不能在模板本身中使用 instanceof
.有没有其他方法可以从模板中检查 thing
的类型,这样编译器就不会报错了? (我通过将我的输入指定为 any
使构建再次运行,但当然,如果可能的话,我想让我的类型检查回来。)
最佳答案
显然编译器尊重 User Defined Type Guards .我只需要在我的组件中定义一个方法:
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>
关于angular - 我可以在 Angular 模板中进行类型缩小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220910/