角8和分配变量

问题描述 投票:-1回答:3

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;

但是它不能正常工作。

javascript angular angular-components angular-input
3个回答
0
投票

具有吸气剂的解决方案:

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>

0
投票

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

-1
投票

尝试这样

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

ngOnInit() {
  this.title product.title;
  this.subtitle = product.categories[0];
  this.description = product.description;
}
© www.soinside.com 2019 - 2024. All rights reserved.