When and why to use a 'tick' in Angular 2?

后端 未结 3 1702
离开以前
离开以前 2021-01-01 12:13

I have seen the following is used in an Angular 2 component class:

setTimeout(()=>{}, 0);

That means, an empty function is called after

3条回答
  •  借酒劲吻你
    2021-01-01 12:31

    I'll add on the answer of Gunter as it is small at the moment.

    He says :

    setTimeout(()=>{}, 0); Causes Angular to run change detection for the whole application

    This is because the setTimeout method has been monkey patched to be intercepted by angular which upon interception triggers change detection. In other words everytime setTimeout is called a change detection happens.

    this could be done like this:

    const temp = window.setTimeout;
    window.setTimeout = (...args) => {
        temp(...args)
        angular.triggerChangeDetection(); // or w.e they use
    }
    

    So the 0 is to make the change detection happen immediately and the empty function is because we don't want to do anything.

提交回复
热议问题