2famous.TV
2famous.TV

Reputation: 470

Angular 2 renders template multiple times

I'm experiencing some problems with Angular 2, as it runs through the template multiple times. It seems like the more routing and components I have, the worse it gets, and it can run through a template as many as 200 times, making the fan on my computer go bananas.

Below is a basic example where I just use the basic quickstart GIT, with no other code added. This particular example runs 4 times.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `{{loop()}}`,
})

export class AppComponent  {
  msg: string = 'hey';
  loop() {
    console.log(this.msg);
  }
}

And the console:

app.component.ts:11 hey
app.component.ts:11 hey
app.component.ts:11 hey
app.component.ts:11 hey

Upvotes: 1

Views: 2205

Answers (1)

Julia Passynkova
Julia Passynkova

Reputation: 17879

loop() will be called in each detection for your component. Try not to call functions in your template. for example, this code will constantly call loop() becuase setInterval causes change detection. You can use ChangeDetection.OnPush

@Component({
  selector: 'my-app',
  template: `{{loop()}}`,
})
export class App  {
  msg: string = 'hey';
  constructor() {
    setInterval(()=> {console.log('x')});
  }
  loop() {
    console.log(this.msg);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Upvotes: 1

Related Questions