Topic: Setting Default Value in Select Input from Dynamically Generated JSON Response

ak.leimrey pro asked 6 years ago


Hello, I've got somewhat of a little problem at my hands. As the question says specifically, I get a JSON from my backend. I transform it into a valid Array Object, so the Material Select can render it. That part works splendidly, but I also need to select to immediately pick the first item that I receive. It's part of the user story. But merely adding the 'selected: true' attribute doesn't do anything. Thanks.

Damian Gemza staff answered 6 years ago


Dear ak.leimrey, The case with which you're facing up is described in our Material Select documentation. For setting up some default value in Select, selected: true property won't work. You have to use two-way data binding to bind some value from your select's array to value of your input. Please take a look at my code: .html:
<div class="row">

<div class="col-md-6 mx-auto my-5">

<mdb-select [(ngModel)]="selectedValue" [options]="dateOptionsSelect" placeholder="Choose time period"></mdb-select>

</div>

</div>

<button class="btn btn-primary waves-light" mdbWavesEffect (click)="getData()">Get Data</button>
.ts:
import { Component } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Component({

selector:'app-root',

templateUrl:'./app.component.html',

styleUrls: ['./app.component.scss']

})

export class AppComponent {

url: string='https://jsonplaceholder.typicode.com/posts';

dateOptionsSelect= [

{ value: '1', label: 'Today', selected: true },

{ value: '2', label: 'Yesterday' },

{ value: '3', label: 'Last 7 days' },

{ value: '4', label: 'Last 30 days' },

{ value: '5', label: 'Last week' },

{ value: '6', label: 'Last month' }

];

selectedValue = '1';

constructor(private http: HttpClient) { }

getData() {

this.http.get(this.url).subscribe(

(data: any) => {

this.dateOptionsSelect= [

{ value: '1', label: data[0].title, selected: true },

{ value: '2', label: data[1].title },

{ value: '3', label: data[2].title },

{ value: '4', label: data[3].title },

{ value: '5', label: data[4].title },

{ value: '6', label: data[5].title },

];

this.selectedValue='1';

}

);

}

}
For me it works like a charm. But please remember to import HttpClientModule and FormsModule to get this work. Best Regards, Damian

ak.leimrey pro commented 6 years ago

Sorry if I sound stubborn, but it doesn't work. At least not in the context of many applications handling REST. My component does call a REST endpoint to receive data to populate the select-box during the ngOnInit lifecycle hook. To make it work, it has to properly wait until the get request has been successfully run, and by using the complete:void callback of the subscribe you can then change it. Also, the [(ngModel)] syntax doesn't appear to work either. I had to use the [ngModel]=someDefaultValue  (ngModelChange)="setDefaultValue($event)" for the implementation to work with async data that has to be initialized with the component

Damian Gemza staff commented 6 years ago

So after your changes do it works fine? I have tried to use my code in OnInit and for me, it works as same as from button. Best Regards, Damian

ak.leimrey pro commented 6 years ago

To clarify: I managed to change it the way I want it to work. Thing is, Damian, your example breaks the very instance you delete the initialization of your dateOptionsSelect. The example works, because you already set the value for each select option and merely overwrite what is being written in the label. However, what if you don't know how many options you're gonna get from the backend? What if you have to create them on the fly? The value doesn't have to be just an ongoing number (something I would always suggest NOT doing, since if I want to pass the outcome of a selected option I would never simply pass an index and certainly not the label). The example has one issue. The HttpClient does asynchronous calls. If you attempt to change the selected value during the subscribe, it would be unable to do so, since it's not clear if the request has ended. So without using the complete: void => callback, you lack control what happens with your data and subsequent method calls that depend on it. I think it's just worth mentioning, in the example, that it would only work in a strictly static application of the select box. Also, another question... The flag "selected: boolean" seems to be without actual function, if it is suggested anyway to use ngModel to pick the default value. It seems like a confusing part for the example. Am I wrong?


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue

  • ForumUser: Pro
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: -
  • Device: -
  • Browser: -
  • OS: -
  • Provided sample code: No
  • Provided link: No
Tags