[英]Element implicitly has an 'any' type because expression of type '"logo"' can't be used to index type 'Object' in Angular
[英]'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type in Object' in *ngFor
我正在嘗試顯示以下 object:
export const articles = {
hardware: ['CPU', 'Motherboard', 'GPU', 'RAM', 'Power Supply'],
Software: ['Operating System', 'Program', 'Web Site'],
compsci: ['Algorithm', 'Programming', 'Data Structure']
}
像這樣:
<h2>Browse through our articles:</h2>
<section *ngFor="let key of keys">
{{key}}
<div *ngIf="myArticles.hasOwnProperty(key)">
<span *ngFor="let arr of myArticles[key]"><app-list-detail [list]="arr"></app-list-detail></span>
</div>
</section>
arr作為list發送到子組件的位置。 但我得到標題中的錯誤。 我認為是因為 TS 無法知道key是否是myArticles的實際屬性,所以我在上面添加了 * ngIf 。
但它仍然不起作用,我不明白為什么。
您可以使用鍵值keyvalue
來迭代對象:
<h2>Browse through our articles:</h2>
<section *ngFor="let entry of articles | keyvalue">
{{entry.key}}
<span *ngFor="let arr of entry.value"><app-list-detail [list]="arr"></app-list-detail></span>
</section>
要克服該錯誤,您需要指定articles
的類型。 您可以將類型指定為:
export const articles: Record<string, string[]> = {
hardware: ['CPU', 'Motherboard', 'GPU', 'RAM', 'Power Supply'],
Software: ['Operating System', 'Program', 'Web Site'],
compsci: ['Algorithm', 'Programming', 'Data Structure']
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.