问题
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