Why is an expression in my app.component.html call

2019-07-28 16:42发布

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条回答
倾城 Initia
2楼-- · 2019-07-28 17:21

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!!

查看更多
登录 后发表回答