Search code examples
angularasynchronousdata-bindingangular2-changedetection

Understanding change detection and async functions in Angular


I am trying to understand the change detection and template updating in Angular. I am actually a little confused.

I have a button and a simple input field. When the button is clicked I change the input field's value to "test". Then make an async function which returns immediately. Then I wait for around 4 seconds using a for loop (for testing purposes).

  • What I expect is: Input field's value becomes "asynched" immediately, since it is an async call.
  • Reality : Input field's value becomes "asynched" after 4 seconds.

Code

  updateField(){
    this.textContentMain.title = "test"
    this.asyncTestFunction();
    for(var i=0;i<3999999999;i++){

    } 
  }

  asyncTestFunction() {
    this._contentSalesTextConfigService.get(this.contentSalesTextConfig).subscribe(item => {
        this.textContentMain.title = "asynced";
    })
  }

Template

<button (click)="updateField()">Update</button>
<input  [ngModel]="textContentMain.title" #titleAccessor="ngModel" name="title" id="title"  type="text" >

Solution

  • Here is the flow of execution, This should clear all your doubts

    // 1. This function will be called as soon as clicked
    updateField(){
        this.textContentMain.title = "test" // 2. changes the value
        this.asyncTestFunction(); // 3. call async function
        for(var i=0;i<3999999999;i++){ // 5. start for loop 
    
        } 
        // 6. end for loop
    }
    
    asyncTestFunction() {
        this._contentSalesTextConfigService.get(this.contentSalesTextConfig) // 4. call the http request
        .subscribe(item => {
            this.textContentMain.title = "asynced"; // 7. asap response is received and for loop finish its execution this wiil be executed.
        })
    }
    

    Why => 7. asap response is received and for loop finish its execution this wiil be executed. (why it waits for "for loop" to finish)?

    For this you have to read event-loop
    Watch this the best video which can explain the key thing behind the scene:

    What the heck is the event loop anyway?