I've developed a component named "foo" that accepts a data object and displays it within an ng-template as its own variable.
The issue arises when the variable inside the ng-template is of type any, lacking proper typing for checking and autocomplete features.
My goal is to pass any type of variable - be it an observable, string, number, object, or any other data type - to the foo component and access the same variable with appropriate typing within the ng-template.
Is it possible to achieve this in Angular?
import { CommonModule } from '@angular/common';
import { Component, ContentChild, Input, TemplateRef } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { of } from 'rxjs';
import 'zone.js';
@Component({
selector: 'foo',
standalone: true,
imports: [CommonModule],
template: `
<div>
<ng-container *ngTemplateOutlet="fooTemplate; context: { data }" />
</div>
`,
})
export class FooComponent {
@ContentChild('foo') fooTemplate!: TemplateRef<unknown>;
@Input() data: any; // <--- type?
}
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, FooComponent],
template: `
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
<foo [data]="person$ | async">
<ng-template #foo let-person="data">
{{ person | json}}
</ng-template>
</foo>
<foo [data]="[1,2,3,4]">
<ng-template #foo let-numbers="data">
{{ numbers | json}}
</ng-template>
</foo>
`,
})
export class App {
name = 'Angular';
person$ = of({
name: 'toto',
age: 3,
});
}
bootstrapApplication(App);