Angular2, view not updating after variable changes in settimeout

后端 未结 4 1177
再見小時候
再見小時候 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

    I had a very similar problem to the OP where even in a basic Angular2 setup changes to bound properties would not be reflected by the view automatically. At this point in time we're using Angular2 2.0.0-rc.6. There was no error message.

    In the end I found the culprit to be a reference to es6-promise.js, which was 'required' by a third party component we use. Somehow this interfered with the core-js reference we are using which is suggested with rc6 in some of the Angular2 tutorials.

    As soon as I got rid of the es6-promise.js reference, the view updated correctly after changing a property on my component (via Promise or timeout).

    Hope this helps somebody some day.

    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 2021-01-17 08:20

    As Vlado said, it should work ;-)

    I think that the angular2-polyfills.js library should be included into your page. I can't see it. This file is essentially a mashup of zone.js and reflect-metadata. Zones take part of the detection of updates.

    You could have a look at this video where Bryan Ford explains what it is: https://www.youtube.com/watch?v=3IqtmUscE_U.

    Hope it helps you, Thierry

    0 讨论(0)
  • 2021-01-17 08:22

    That should work. Do you have any other errors in console?

    @Component({
     selector: 'my-app',
     template: `<h1>Hello {{title}}</h1>`
    })
    export class App {
     public title: string = "World";
     constructor() {
       setTimeout(() => {
        this.title = "Brave New World"
       }, 1000);)
     }
    }
    

    Look at this Plunker: http://plnkr.co/edit/XaL4GoqFd9aisOYIhuXq?p=preview

    0 讨论(0)
提交回复
热议问题