Issue
How can parent component recognise type of let-content
which comes from ngTemplateOutletContext
? Now {{content.type}}
works correctly, but IDE says:
unresolved variable type
How can I type it as Video
?
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>
Solution
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
You can try to silence the IDE warning using $any()
https://angular.io/guide/template-syntax#the-any-type-cast-function
<ng-template #tileTemplate let-content>
<h5 class="tile__type">{{$any(content).type}}</h5>
</ng-template>
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; }
Answered By - Reactgular
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.