在我的应用程序中,有一个父组件,其中包含表示不同水果的对象列表。当用户选择水果时,其数据将传递到子组件,该子组件 将所有数据显示为详细信息。
<app-details
[fruit]="selectedFruit"
></app-details>
在详细信息模板中:
<div class="fruit-details">
<h1>{{fruit.name}}</h1>
<h1>{{fruit.color}}</h1>
<h1>{{fruit.description}}</h1>
</div>
"fruit"属性设置为在详细信息组件中键入对象。@Input()fruit: Object;
发生错误,指出类似Property 'description' does not exist on type 'Object'
的内容。不将"fruit"属性设置为"对象"的数据类型可以解决问题。但是如何在不删除数据类型的情况下解决此问题。
声明一个Fruit
接口,然后将其用作类型:
interface Fruit {
name: string;
color: string;
description: string;
}
@Input()fruit: Fruit;
如何使用 @Input((水果:字符串,字符串化您选择的水果
JSON.stringify(selectedFruit)
在详细信息组件中解析它:
let parseFruit = JSON.parse(this.fruit);
console.log(parseFruit);