angularnativescriptlistpicker

Programmatically set ListPicker.selectedIndex in Nativescript + Angular App


I am working on my first Nativescript App and I have chosen Angular for the framework. I've run into a little snag with a ListPicker component. I am able to render the component with a list of items and can initially set the selectedIndex; however, when I later try to change the selectedIndex programmatically (e.g. from 0 to 2) the value displayed in the UI does not update (testing on Android). Surprisingly, the selectedIndexChange callback does log the correct new selectedIndex. How do I force the UI to display the correct value for the new selectedIndex?


Solution

  • ngZone.run can be used to help force the UI to recognize a change in data:

    import { NgZone } from "@angular/core";
    
    export class TestComponent {
    
        selectedIndex: number;
    
        constructor(private ngZone: NgZone) {}
    
        testMethod(pos: number): void {
            this.ngZone.run(() => {
                this.selectedIndex = pos;
            });
        }
    }