Why is an expression in my app.component.html called multiple times?

我的未来我决定 提交于 2019-12-11 06:34:01

问题


I traced the evaluation of an expression in the app.component.html main template and i realized that the trace appeared exactly 5 times each time i refresh or click any page. I then placed a trace in the ngOnInit of app.component.ts and it executes only once as expected... Only the expression in the html file gets called multiple times !

Main routes definitions:

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  //{ path: '',  component: DashboardComponent },
  { path: 'dashboard',  
    component: DashboardComponent,
    canActivate: [AuthGuard], 
    children:[
      {
        path:'main',
        component: DashMainComponent
      },
      {
        path:'config',
        component: DashConfigComponent
      },
      {
        path:'projects',
        component: DashProjectsComponent
      }
    ]
  },
  { path: 'signin',  component: SigninComponent },
  { path: 'signup', component: SignupComponent },
  { path: 'inventory', component: InventoryComponent },
  { path: 'project', component: ProjectComponent },
  { path: 'timesheet', component: TimesheetComponent },
  { path: 'messaging', component: MessagingComponent },
  { path: 'profile', component: ProfileComponent }
];

Top of the html file:

<div id="app">
    {{test}}

app.component.ts:

import { Component, OnInit } from '@angular/core';
import {AuthService} from './auth.service';
import { Router, ActivatedRoute } from '@angular/router';
import {Config} from './config.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {


  constructor(private authService:AuthService, private router:Router) { }
  ngOnInit(){
    console.log("init");
  }

  get test(){
    console.log("test");
    return "";
  }



}

Thanks for any help !


回答1:


Its how Angular does template expression evaluation,

Angular executes template expressions after every change detection cycle. Change detection cycles are triggered by many asynchronous activities such as promise resolutions, http results, timer events, keypresses and mouse moves.

Read more about it here.

Hope this helps!!



来源:https://stackoverflow.com/questions/43401350/why-is-an-expression-in-my-app-component-html-called-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!