关于前端:Angular-Component-里-get-关键字修饰的属性的用法

8次阅读

共计 1492 个字符,预计需要花费 4 分钟才能阅读完成。

在 Angular 中,get 关键字用于定义一个拜访器属性(accessor property),它是一种非凡的属性,能够通过在类中定义一个带有 get 关键字的办法来实现。当拜访这个属性时,会调用这个 get 办法,并返回该办法的返回值。这种办法使得拜访属性时能够执行一些自定义操作,例如计算属性值、验证数据或触发其余操作。在 Angular 组件中,get 关键字通常与输出(@Input())属性和输入(@Output())属性联合应用,以实现更灵便的组件数据绑定。

上面咱们将通过一个示例具体介绍在 Angular 组件中应用 get 关键字润饰的属性的用法。

假如咱们正在开发一个在线商城利用,须要构建一个名为 ProductListComponent 的组件,用于展现产品列表。每个产品有一个名字、一个价格和一个库存量。咱们心愿建设一个能够依据库存量为每个产品设置不同背景色的性能。例如,库存量大于 10 时显示绿色背景,库存量在 5 到 10 之间时显示黄色背景,库存量小于 5 时显示红色背景。

首先,咱们须要定义一个 Product 类来示意产品:

// product.ts
export class Product {
  constructor(
    public name: string,
    public price: number,
    public stock: number
  ) {}}

接下来,咱们创立一个名为 ProductListComponent 的组件,并在其模板中应用 ngFor 指令遍历产品列表,为每个产品创立一个列表项。为了实现依据库存量设置不同背景色的性能,咱们能够应用 get 关键字定义一个拜访器属性 stockBackgroundColor,并依据库存量返回相应的背景色。

// product-list.component.ts
import {Component} from '@angular/core';
import {Product} from './product';

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent {products: Product[] = [new Product('Product 1', 49.99, 5),
    new Product('Product 2', 99.99, 12),
    new Product('Product 3', 29.99, 3),
  ];

  get stockBackgroundColor(): string {if (this.stock > 10) {return 'green';} else if (this.stock > 5) {return 'yellow';} else {return 'red';}
  }
}

ProductListComponent 的模板中,咱们须要为每个产品的列表项设置一个动静背景色,能够应用 Angular 的款式绑定语法将 stockBackgroundColor 属性绑定到 background-color 款式属性上。

<!-- product-list.component.html -->
<ul>
  <li *ngFor="let product of products"
      [style.backgroundColor]="stockBackgroundColor">
    {{product.name}} - {{product.price}} - {{product.stock}}
  </li>
</ul>
正文完
 0