角度6-防止点击功能发生变化

时间:2018-10-19 14:55:40

标签: html angular typescript angular6

我有一个function返回一个随机数:

@Component({
    selector: '...',
    templateUrl: '...',
    styleUrls: ['...'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Component {

    randomPerc(min, max): number {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

}

并且我仅在这样的HTML模板中使用此功能(在许多地方):

<div [style.width.%]='randomPerc(20, 70)'></div>

“问题”是,当我单击页面上的某处时,百分比会立即更改。但是我想避免这种情况-我希望在首次调用该函数后该百分比为静态

我曾想创建一个常量全局变量,但是由于我多次使用此函数,因此无法正常工作。 (我希望每次使用时都使用不同的随机数)

1 个答案:

答案 0 :(得分:2)

方法1-将值缓存在Map对象中

您可以为每个元素使用不同的键来调用该方法,将结果缓存在Map对象中,并在针对同一元素再次调用该方法时重新使用它:

<div [style.width.%]="randomPerc('key1', 20, 70)"></div>
<div [style.width.%]="randomPerc('key2', 10, 50)"></div>
<div [style.width.%]="randomPerc('key3', 25, 90)"></div>

<div *ngFor="let item of items; let i = index">
  <div [style.width.%]="randomPerc('item' + i, 25, 90)"></div>
</div>
private widths = new Map<string, number>();

randomPerc(key: string, min: number, max: number): number {
  if (!this.widths.has(key)) {
    this.widths.set(key, Math.floor(Math.random() * (max - min + 1) + min));
  }
  return this.widths.get(key);
}

有关演示,请参见this stackblitz


方法2-使用自定义指令

另一种方法是定义一个自定义指令。在下面的示例中,最小和最大百分比宽度定义为具有默认值的两个输入参数。由于样式属性仅在ngOnInit中的元素上设置,因此以后在更改检测时不会对其进行修改。

import { Directive, Input, ElementRef, OnInit } from '@angular/core';

@Directive({
  selector: "[randomWidth]"
})

export class RandomWidthDirective implements OnInit {

  @Input() minRandom: number = 20;
  @Input() maxRandom: number = 70;

  constructor(private el: ElementRef) { }

  ngOnInit() {
    let value = Math.floor(Math.random() * (this.maxRandom - this.minRandom + 1) + this.minRandom);
    this.el.nativeElement.style.width = `${value}%`;
  }
}

该指令使用默认参数或使用不同的值覆盖它们,从而将其应用于模板中的元素:

<div randomWidth></div>
<div randomWidth [minRandom]="10"></div>
<div randomWidth [minRandom]="5" [maxRandom]="95"></div>

有关演示,请参见this stackblitz