在Angular 4中封装每个实例的变量



我有一个应用程序,其中 ProductComponent被多次重复为列表。在此ProductComponent中,有一个称为this.showPriceLoadingText的public boolean本地变量。但是,当在一个实例中更新此变量时,列表中的所有其他实例都将更新。我以为ES6封装在其所在的实例/范围内的变量,显然不是。

如何使此变量独立行为?

class ProductComponent(){
 public showBasketLoadingText: boolean;
 public addingToBasketText: string = "";
 constructor() {
    this.showBasketLoadingText = false;
    this.addingToBasketText = environment.configurations.uiConfig.addingToBasketText;
 }
QuickAddtoCart(product: Product) {
    this.showBasketLoadingText = true;
    //DO STUFF
    let _self = this;
    setTimeout(function(){
        _self.showBasketLoadingText = false;
    }, 1000);
  }
}

html:

<span *ngIf="(!this.showBasketLoadingText)"><i class="fa fa-cart-arrow-down" aria-hidden="true"></i> Add to basket</span>
<span *ngIf="(this.showBasketLoadingText)">{{ addingToBasketText }}</span>

您应该使用这种方式(箭头符号)保存this

setTimeout(() => {this.showBasketLoadingText = false;}, 1000);

更多信息在这里

箭头功能没有自己的功能;这个值的值 使用封闭执行上下文。

现在已经解决了……我发现该组件实际上仅是一个产品列表,而不是单个产品。浪费时间

表示歉意

最新更新