Force Angular 2 data update view

I have an Angular 2 component (beta 0) whose value changes based on code outside of Angular. I can listen to this and execute the code whenever such a change has occurred, but I don’t know which code to run to update the Angular 2 view.

If I take the link to start NgZone when my component is initialized, I can call ngZone.run(function() { /* do nothing */});and force update it. However, I don’t know what I should do, and even if it is, I don’t know what is the legal way to get the ngZone link of my application.

How can I do it?

[edit] In Angular 1.x, I would do $scope.$apply(), but not in Angular 2. Other people suggested to do it setTimeout(function() { /* do stuff */ }), but it did not seem to pick up NgZone (it is connected by a normal zone), and therefore does not cause a change check.

+4
source share
1 answer

I understood that. Unlike Angular 1, not all injection dependencies for components can be inferred from the parameter name. In my case, I accessed NgZone and then linked the changes in the zone as follows:

customSelect = ng.core
    .Component({
        selector: 'custom-select',
        templateUrl: 'select.html',
        properties:[
            'valueProperty:valueProperty',
            'value:value',
            'options:options'
        ]
    })
    .Class({
        constructor:[ng.core.NgZone, function(zone) {
            this.zone = zone;
        }],
        ngOnInit:function() {
            this.unbindChanges = this.valueProperty.bindChanges(function() {
                this.zone.run(function() {
                    this.value = this.valueProperty.currentValue();
                }.bind(this));
            }.bind(this));
        },
        ngOnDestroy:function() {
            this.unbindChanges();
        }
    });
0
source

Source: https://habr.com/ru/post/1620449/


All Articles