问题描述
父组件如何识别来自 ngTemplateOutletContext
的 let-content
类型?现在 {{content.type}}
可以正常工作,但是IDE会说:
How can parent component recognise type of let-content
which comes from ngTemplateOutletContext
? Now {{content.type}}
works correctly, but IDE says:
如何将其键入为视频
?
parent.component.ts:
export interface Video {
id: number;
duration: number;
type: string;
}
public videos: Video = [{id: 1, duration: 30, type: 'documentary'}];
parent.component.html:
<ul>
<li *ngFor="let video of videos">
<tile [bodyTemplate]="tileTemplate" [content]="video"></app-card>
</li>
</ul>
<ng-template #tileTemplate let-content>
<h5 class="tile__type">{{content.type}}</h5>
</ng-template>
tile.component.ts:
@Component({
selector: 'tile',
templateUrl: './tile.component.html',
styleUrls: ['./tile.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CardComponent {
@Input() tileTemplate: TemplateRef<any>;
@Input() content: Video;
}
tile.component.html:
<div
...
<ng-container
[ngTemplateOutlet]="tileTemplate"
[ngTemplateOutletContext]="{ $implicit: content }">
</ng-container>
...
</div>
推荐答案
let-*
变量没有类型推断. let-
上下文是Angular的微语法解析器的一部分,并且由于没有明确的来源,IDE无法推断类型.
There is no type inference for let-*
variables. The let-
context is part of the micro syntax parser for Angular, and an IDE can not infer the type as there is no clear origin.
https://gist.github.com/mhevery/d3530294cff2e4a1b3fe15ff75d08855
您可以尝试使用 $ any()
https://angular.io/guide/template-语法#the-any-type-cast-function
<ng-template #tileTemplate let-content>
<h5 class="tile__type">{{$any(content).type}}</h5>
</ng-template>
您可以使用函数 force 进行类型推断
You can force type inference by using a function
<ng-template #tileTemplate let-content>
<h5 class="tile__type">{{toVideo(content).type}}</h5>
</ng-template>
public toVideo(value: any): Video { return value as Video; }
这篇关于ng-template-类型变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!