【问题标题】:Angular - ngFor change variable after clickAngular - ngFor 单击后更改变量
【发布时间】:2018-06-03 04:06:03
【问题描述】:

所以,假设我有这个 ngFor 循环:

<ng-container*ngFor="let rate of [1,2,3,4,5]">
    <div (click)="change()">{{myVariable}}</div>
</ng-container>

我的模板中有变量 5 次显示,我想要做的是在单击它后更改变量,即被单击的变量和上一个变量被更改,而下一个变量保持原样。 当我有:

export class StarRatingComponent {
  myVariable = 'a';

  change() {
    this.myVariable = "b";
  }
}

如果我单击a,则所有内容都更改为b。如何仅对单击的项目和以前的项目应用此更改?所以例如。从aaaaabbbaa

【问题讨论】:

    标签: angular loops variables ngfor


    【解决方案1】:

    只需传递所选评级的值。

    这样的事情可能会奏效:

    <ng-container*ngFor="let rate of [1,2,3,4,5]">
      <div (click)="change(myVariable)">{{myVariable}}</div>
    </ng-container>
    

    然后在组件中,按索引跟踪:

    export class RatingCmp {
      rating: string = '1';
      change(rating) {
        this.rating = rating;
      }
    }
    

    【讨论】:

    • 可悲的是,它不起作用。 + 我知道如何接收点击项目的数量,所以如果有人点击第三个 a 我得到“3”,但不知道如何将这个“a”更改为“b”,但感谢您的帮助和时间。
    • 在这种情况下,我们缺少信息。你到底想改变什么?您的组件上只有一个“a”,当然它已全部更改?
    【解决方案2】:

    尝试以下方法:

    <ng-container*ngFor="let value of values; index as i">
        <div (click)="change(i)">{{value}}</div>
    </ng-container>
    
    export class StarRatingComponent {
      values = this.generateValues('a',5);
    
      private generateValues(val: string, times: number): string[]{
        const result: string[] = [];
        while(--times >= 0){
           result.push(val);
        }
        return result;
      } 
    
      change(index: number) {
         while(index >= 0){
           this.values[index] = 'b';
           index--;
         }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2016-04-24
      • 2016-09-18
      • 2019-01-26
      相关资源
      最近更新 更多