-1

product.html我有以下代码:

<h3>{{product.title}}</h3>
<h4>{{product.categories[0]}}</h4>
<p>{{product.description}}</p>

我得到了productvia 输入(初始值为空),所以product.ts看起来像这样:

 @Input() product: Product = {title: '', categories: [''], description: ''};

我希望product.html看起来像这样:

<h3>{{title}}</h3>
<h4>{{subtitle}}</h4>
<p>{{description}}</p>

我的问题是,我怎样才能做到这一点?

我尝试让变量title, subtitle, description简单地指向product的属性 ( title, categories[0], description),所以product.ts看起来像这样:

 @Input() product: Product = {title: '', categories: [''], description: ''};
 title = product.title;
 subtitle = product.categories[0];
 description = product.description;

但它工作不正常。

4

3 回答 3

1

带有吸气剂的解决方案:

get title(): string {
  return this.product.title;
}

get subtitle(): string {
  return this.product.categories[0];
}

get description(): string{
  return this.product.description;
}

进入模板:

<h3>{{title}}</h3>
<h4>{{subtitle}}</h4>
<p>{{description}}</p>
于 2019-12-31T11:01:02.340 回答
1

您可以定义您的属性,然后在ngOnChanges生命周期挂钩中设置它们。

... definition
title: string;
subtitle: string;
description: string;
... inside ngOnChanges
this.title = this.product.title;
this.subtitle = this.product.categories[0];
this.description = this.product.description;

另一种选择是使用函数来获取值:

title = () => this.product.title;
subtitle = () => thisproduct.categories[0];
description = () => this.product.description;

并在您的视图中将它们用作:

{{title()}}
{{subtitle()}}
{{description()}}
于 2019-12-31T10:56:30.487 回答
0

像这样试试

 title: string;
 subtitle: string;
 description: string;

ngOnInit() {
  this.title product.title;
  this.subtitle = product.categories[0];
  this.description = product.description;
}
于 2019-12-31T10:57:22.473 回答