具有计算的角模板变量

  • 本文关键字:变量 计算 angular
  • 更新时间 :
  • 英文 :


在Angularjs中,您可以做:

<div ng-controller="ExampleController">
  <div ng-init="a=1 + 5 -2">{{a}}
  </div>
</div>

//a = 4

Angular 5/6/7中的等效物是什么?我有一个带有数字的ngfor循环,我需要在底部显示总数。

@Component({
  selector: 'my-app',
  template: `
  <div *ngFor="let i of arr">{{random()}}</div>
  <b>Total: _____?</b>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  arr = new Array(10)
  random(){
    return  Math.floor((Math.random()*10));
  }
  name = 'Angular';
}

https://stackblitz.com/edit/angular-ij5uxc

谢谢

您应该依靠事件编程。开始使用RXJ的全部潜力!

在这个sackblitz中,我向您展示了如何做:创建一个是您的值的Subject。然后,您可以创建一个可观察到的是数组值的总和。

使用此解决方案,您只需将新值推向数组,并且由于async管道,它会在视图中自动更新。

import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { take, map } from 'rxjs/operators';
@Component({
  selector: 'my-app',
  template: `
  <div>
    <button (click)="addValueToSub()">
      Add a new value to the array
    </button>
  </div>
  <div *ngFor="let value of (sub | async)">{{value}}</div>
  <b>Total ? {{ total | async }} !</b>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  sub = new BehaviorSubject([]);
  total = this.sub.pipe(
    map(values => values.reduce((acc, curr) => acc + curr, 0))
  );
  constructor() {
    for (const i of new Array(10)) {
      this.addValueToSub();
    }
  }
  random() {
    return Math.floor((Math.random() * 10));
  }
  addValueToSub(value = this.random()) {
    this.sub.pipe(
      take(1)
    ).subscribe(values => {
      values.push(value);
      this.sub.next(values);
    });
  }
}
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
  <div *ngFor="let i of arr">{{random()}}</div>
  <b>Total: {{total}}?</b>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  arr = new Array(10)
  total = 0;
  random(){
    this.total += Math.floor((Math.random()*10));
    return this.total  
  }
  name = 'Angular';
}

我将生成一个随机数数组,然后只使用函数来计算总和,请参见此处。

arr: number[] = [];
arrayLength = 0;
ngOnInit() {    
  while (this.arrayLength < 10) {
    this.arr[this.arrayLength] = this.random();
    this.arrayLength++;
  }
}
random(): number {
  return  Math.floor((Math.random()*10));
}  
getTotal(): number {
  return this.arr.reduce(function(a, b) { return a + b; });
}

最新更新