Angular2, view not updating after variable changes in settimeout

后端 未结 4 1175
再見小時候
再見小時候 2021-01-17 07:47

I am trying to setup my first angular2 application as an experiment and am using the latest beta release.

I am facing a weird issue where the variable i am using in

4条回答
  •  走了就别回头了
    2021-01-17 08:17

    In Angular2 (~2.1.2) another way to make it work is through the ChangeDetectorRef class. The original question code would look like this:

    import { 
      ChangeDetectorRef
      // ... other imports here
    } from '@angular/core';
    
     @Component({
        selector: "my-app",
        bindings: []
    })
    
    @View({
        templateUrl: "templates/main.component.html",
        styleUrls: ['styles/out/components/main.component.css']
    })
    
    export class MainComponent {
    
        public test2 = "initial text";
    
        constructor(private cd: ChangeDetectorRef) {
            setTimeout(() => {
                this.test2 = "updated text"; 
    
                // as stated by the angular team: the following is required, otherwise the view will not be updated
                this.cd.markForCheck();
    
            }, 500);
        }
    }
    

提交回复
热议问题