【问题标题】:Angular 8 and assigning variablesAngular 8和分配变量
【发布时间】:2020-04-19 22:09:52
【问题描述】:

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;

但它不能正常工作。

【问题讨论】:

  • 定义访问器?例如。 get title(): string { return this.product.title; }
  • 设置ngOnInit钩子内的所有实例值。
  • @SiddharthPal 如果输入发生变化,它们将不会被重置。

标签: javascript angular angular-components angular-input


【解决方案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()}}

【讨论】:

  • 非常感谢您的回答!我已经尝试过 ngOnInit,但还没有考虑过 ngOnChanges,很高兴(终于)看到它可以在哪里以及如何使用。
【解决方案2】:

这样试试

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

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

【讨论】:

    【解决方案3】:

    使用 getter 的解决方案:

    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>
    

    【讨论】:

    • 非常感谢您的回答!我从未见过 Angular 中使用的 getter 和 setter(作为新手),这是常见的做法吗?如果可以给两个,我也会给你的答案打勾。
    • 这不是 Angular 特有的,而是 Typescript (typescriptlang.org/docs/handbook/classes.html) 特有的,是的,这是一种常见的做法。
    猜你喜欢
    • 2014-09-07
    • 1970-01-01
    • 2014-10-26
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多