NativeScript / nativescript-angular

Integrating NativeScript with Angular
http://docs.nativescript.org/angular/tutorial/ng-chapter-0
Apache License 2.0
1.22k stars 241 forks source link

SegmentedBar/TabView `selectedIndexChange` event fired before `selectedIndex` property binding has set the value #1379

Open jamie-pate opened 6 years ago

jamie-pate commented 6 years ago

If you place a SegmentedBar inside an *ngIf the selectedIndexChange event is fired before the property value for selectedIndex is pulled from the component. This may cause the event handler to set the value of selectedIndex to 0 (or array.indexOf(0) if you are getting/setting some other variable on it's index within an array of possible values)

Affects TabView component also, but slightly differently. The correct tab remains selected even though the model value has changed? (is it somehow skipping change detection?)

tsonevn commented 6 years ago

Hi @jamie-pate, Thank you for the attached sample project. We will investigate it further and will provide more info about it. Meanwhile, you can set up a variable, which can be used for skipping the first execution of the event. For example:

public test = false
onValueChange(event) {
if(test){
// your code here
}
test = true;
}
jamie-pate commented 6 years ago

I think a better way to skip the first execution is to check if event.oldValue is -1 (see commented code in the sample)

    onValueChange(event) {
        // https://github.com/NativeScript/nativescript-angular/issues/1066
        const value = 'newIndex' in event ? event.newIndex : event.value,
            oldValue = 'oldIndex' in event ? event.oldIndex : event.oldValue,
            selectedIndex = event.object.selectedIndex,

        if (oldValue != -1) {
            this.model.value = this.STRS[value];
        }
    }
pedromorgan commented 6 years ago

Experiencing same issue, even without binding the "selectedIndex".. Maybe the selectedIndexChanged event is fired before "ui loading" is complete ?

<SegmentedBar selectedIndexChanged="onTabChanged">...

My workaround, following on from @jamie-pate

export function onTabChanged(args: any){
    console.log("vals=", args.oldValue, args.newValue);
   // outputs > JS: vals= undefined undefined
    if(!args.oldValue) {
        return; // stops crash
    }
   // do things
}