I am working on generic component where list view can be utilized by other components. But the issue is data format is different for each component. In my project I can’t use type any[] which will cause linting issues that I can’t skip also.
list-view.component.html(shared component)
<div *ngFor="let list of lists">
<ng-template #defaultTemplate>
<p> {{list}}</p>
</ng-template>
<ng-container
[ngTemplateOutlet]="optionTemplate || defaultTemplate"
[ngTemplateOutletContext]="{ $implicit: list}"
>
</ng-container>
</div>
list-view.component.ts
import {Component,ContentChild,EventEmitter,Input,Output,TemplateRef} from '@angular/core';
export interface listData{
id: number;
brand: string;
model: string;
url: string;
}
@Component({
selector: 'app-my-selector',
templateUrl: './my-selector.component.html',
})
export class MySelectorComponent {
@Input() lists: listData; **// can't use any[], because of linting issue.**
@ContentChild('optionTemplate', { static: false }) optionTemplate: TemplateRef;
constructor() {}
}
test1.component.html
<div class="container">
<app-my-selector [lists]="list">
<ng-template #optionTemplate let-list>
<img src="{{list.url}}" alt="{{list.model}}">
<p>{{list.brand}}: {{list.model}}</p>
</ng-template>
</app-my-selector>
</div>
test1.component.ts
import { Component } from '@angular/core';
export interface listData{
id: number;
brand: string;
model: string;
url: string;
}
@Component({
selector: 'app-test1',
templateUrl: './test1.component.html',
})
export class Test1Component {
list: listData= [
{
id: 1,
brand: 'TATA',
model: 'Indica - 2008',
url: '/indica-img.jpg'
},
{
id: 2,
brand: 'Suzuki',
model: 'Swift - 2011',
url: '/swift-img.jpg'
}
];
constructor() {}
}
test2.component.html
<div class="container">
<app-my-selector [lists]="list"></app-my-selector>
</div>
test2.component.ts
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-test2",
templateUrl: "./test2.component.html",
})
export class Test2Component {
list: string[]; **// this is where causing the issue.**
constructor() {}
ngOnInit() {
this.list = ['Harley Davidson','Bajaj','Triumph'];
}
}
If I run the above code I am getting Type ‘string[]’ is not assignable to type ‘listData[]’ in test2.component.html. Because test1 component is array of object data & test2 component is array data. So with out using any[] how can I achieve this.