0

Let say I have this component with the following template

<div *ngFor="let t of test">{{t}}</div>

And this code

  test: number[] = [1, 2, 3];
  ngOnInit() {
    this.test = this.test.reduce((a, b) => {
      a.push(b * 10);
      return a;
    }, []);
    setTimeout(() => {
      this.test.push(4);
    }, 3000);
  }

This will be result in this

10
20
30
4 // not what I was looking for

However if I decide to move the code in a method getTest()

<div *ngFor="let t of getTest()">{{t}}</div>

with the code

  getTest(): number[] {
    return this.test.reduce((a, b) => {
      a.push(b * 10);
      return a;
    }, []);
  }

Then the delayed value will show as 40 which is what I was looking for.

Is this a valid implementation or is resource consuming? getTest() method seems to be called quite often.

In a bigger picture I'm trying to add / remove / update items in an array and show a reduced version of that array on screen.

1
  • Of course it will be called quite often Commented Nov 11, 2017 at 16:24

2 Answers 2

2

If you bind to a method, it will be called every time Angular runs change detection. This can become a serious performance burden.

It's better to assign the result of the method to a field and bind to the field instead. Change detection with fields is extremely efficient.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use Observable using async pipe like (change rxjs part to your logic)

import { Observable } from 'rxjs/Observable';
import { from } from 'rxjs/observable/from';
import { of } from 'rxjs/observable/of';
import { reduce, concatMap, delay } from 'rxjs/operators';

test: number[] = [1, 2, 3];
$test:Observable<number>;

ngOnInit() {
    this.$test = from(this.test)
      .pipe(
        concatMap(x => of(40)),
        delay(1000),
        reduce((acc, current) => {
          return  acc + current
        },0)
      );
}

in the view

{{$test | async}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.