Search code examples
angularnebular

Angular 8 Dropdown Options Default Last New Value After Update ArrayList


I am using Angular 8 (TypeScript).

I want to select by default the last value agregated in array collection after call service and update the value of array, But always show the placeholder. How can I do it?

<nb-select [(selected)]="selectedNumberCase" 
           placeholder="Select value" shape="round" size="small" 
            class="col-md-7 custom-padding" >
    <nb-option *ngFor="let item of caseNumberArray" (click)="onMenuItemSelected(item.value)"[value]="item.id">{{item.value}}</nb-option>
</nb-select>


populateNumberCase(newId:string,newValue:string){
    this.caseNumberArray.push({
        id:element.newId,
        value:element.newValue
    });
}

callService(){
    .......do something
    this.populateNumberCase(result.Id,result.Value);
    this.selectedNumberCase = result.Value;
}

Solution

  • Try this.

    Assuming You will be having the array object in this variable Just

    Ininitalize a variable;

    selectedOption;
    

    copy the below line in ngOnit() function.

    this.selectedOption= this.selectedNumberCase[this.selectedNumberCase.length-1];
    

    Template Code::

    <nb-select [(selected)]="selectedOption" placeholder="Select value" shape="round" size="small" 
                class="col-md-7 custom-padding" >
          <nb-option
            *ngFor="let item of caseNumberArray"
            (selectionChange)="onMenuItemSelected(item.value)"
            [(value)]="item.id">
            {{ item.value}}
          </nb-option>
        </nb-select>