[英]Error in *ngFor with KeyValuePipe: ngtsc(2322)
我有以下類型
type ParentKeys = "mum" | "dad";
type ChildKeys = "alice" | "frank";
type Parents = {
[parentKey in ParentKeys]: {
children: {
[childKey in ChildKeys]: {
parent: parentKey;
key: childKey;
};
}[ChildKeys][];
};
};
也就是說,內部child
對象{ parent, key }
安裝在樹結構中,在它們的下面。 父母; 允許所有parent-child
配對。 例如檢查
const parents: Parents = {
mum: {
children: [
{ parent: "mum", key: "alice", },
],
},
dad: {
children: [
{ parent: "dad", key: "frank", },
{ parent: "dad", key: "alice", },
],
},
};
現在,如果我在 Angular 模板中使用parents
級
<div *ngFor="let parent of parents | keyvalue">
<div *ngFor="let child of parent.value.children">
<div>child {{child.key}} of parent {{child.parent}}</div>
</div>
</div>
我得到錯誤
Type
'(
{ parent: "mum"; key: "alice"; } |
{ parent: "mum"; key: "frank"; }
)[] |
(
{ parent: "dad"; key: "alice"; } |
{ parent: "dad"; key: "frank"; }
)[]'
is not assignable to type
'(
(
{ parent: "mum"; key: "alice"; } |
{ parent: "mum"; key: "frank"; }
)[] &
NgIterable<
{ parent: "mum"; key: "alice"; } |
{ parent: "mum"; key: "frank"; }
>
) | null | undefined'
.ngtsc(2322)
當然這可以使用$any()
來解決,但顯然我的類型或KeyValuePipe
有問題。
type Parents = { [parentKey in ParentKeys]: { children: { parent: ParentKeys, key: ChildKeys }[]; }; };
問題是孩子 object 的打字過於復雜。
問題在於自己的鍵值keyvalue
與*ngFor
交互。
以下html
作品:
<div *ngFor="let parent of parents | keyvalue"> <div *ngFor="let child of parents[parent.key].children"> <div>child {{ child.key }} of parent {{ child.parent }}</div> </div> </div>
主要的不同是我們調用parents[parent.key]
而不是我們調用parent.value
。 這樣做意味着我們獲得了原始 object 中存儲的值。這是因為鍵值結合*ngFor
修改了keyvalue
,導致其失去了可迭代性並引發了錯誤。
像這樣簡單地改變它
type Parents = {
[parentKey in ParentKeys]: {
children: Array<{
parent: ParentKeys;
key: ChildKeys;
}>;
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.