Reputation: 668
I'm relatively new to TypeScript and it keeps complaining that variables has type "unknown", so I decided to create an interface to fix this problem. But I can't manage to find a solution that works. This is what I've come with so far:
the data I want to use comes from a json that looks like this data.json, this json is simplified alot:
{
"userName":"usernamedummy",
"projects":{
"key1":{
"projname":"dummyname0",
"layers":{
"keyinside1":{
"layername":"dummylayername0",
}
}
},
"key2":{
"projname":"dummyname",
"layers":{
"keyinside2":{
"layername":"dummylayername"
}
}
}
}
my main component looks like this:
import { Component, Input, Output, EventEmitter } from '@angular/core';
import data from './data.json';
export interface Project {
[key: string]: {
projname: string;
layers: {
[key: string]: {
layername: string;
};
};
};
}
@Component({
selector: 'app-layers',
templateUrl: './layers.component.html',
styleUrls: ['./layers.component.less'],
})
export class LayersComponent {
layerListSource: Project;
constructor() {
this.layerListSource = data.projects;
}
}
and does a *ngFor with another component like this:
<li *ngFor="let project of layerListSource| keyvalue">
<app-layer-dropdown [project]="project"></app-layer-dropdown>
</li>
in the other component it looks like this:
import { Component, Input, OnInit } from '@angular/core';
import { Project } from '../layers.component';
@Component({
selector: 'app-layer-dropdown',
templateUrl: './layer-dropdown.component.html',
styleUrls: ['./layer-dropdown.component.less'],
})
export class LayerDropdownComponent implements OnInit {
@Input() project!: Project;
open: boolean;
constructor() {
this.open = false;
}
ngOnInit(): void {
console.log(this.project)
}
}
Having this creates this problem:
Upvotes: 1
Views: 174
Reputation: 5504
The KeyValuePipe transforms your list into key/value pairs, so you'll need to bind to the value:
<li *ngFor="let project of layerListSource| keyvalue">
<app-layer-dropdown [project]="project.value"></app-layer-dropdown>
</li>
See https://angular.io/api/common/KeyValuePipe for reference.
[edit] also, in your layer component, you'll probably have to change the interface, because what you are binding there isn't the dict, it's the values of the dict:
export interface LayerDict {
[key: string]: {
layername: string;
};
}
export interface Project {
projname: string;
layers: LayerDict;
}
export interface ProjectDict {
[key: string]: Project ;
}
// LayersComponent
layerListSource: ProjectDict;
// LayerDropdownComponent
@Input() project!: Project;
Upvotes: 2