Angular8和赋值变量

Angular 8 and assigning variables

product.html中我有以下代码:

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

我通过输入获得了 product(初始值为空),所以 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;

但它无法正常工作。

您可以定义您的属性,然后在 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()}}

这样试试

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

ngOnInit() {
  this.title product.title;
  this.subtitle = product.categories[0];
  this.description = product.description;
}

吸气剂解决方案:

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>