Fill in dropdown from json table - json

So ...i have url (say... http://localhost:8080/website/country) that I target to get this list:
What i want is to populate dropdown with list of county names so user can pick one.
I also did dropdown in html
I am using Angular 2, i have service in which I set to get url from database
I'm sure that I have mistake, so need help :D Thanks
Edit: this is component, if could help

EDIT:
It seems that there is trouble in your component.
First of all, you have to trigger the request which will retrieve the countries and assign the response.
It will looks like following (note we assign the Observable):
#Component(...)
export class CompanyTemplatePopupComponent {
countries;
ngOnInit(){
countries = this.companyService.getCountries();
// or whichever method you need to retrieve the list of countries
}
}
Then in your template (note the use of async pipe):
<option *ngFor="let country of countries | async" [value]="country.id"> {{ country.name }} </option>

html code will be
<select #countriesSelect class=custom-dropdown">
<option selected disabled>Select Country</option>
<option *ngFor="let country of countries: [value]="country.id">{{country.name}}</option>
</select>
In ts code you have to getAllCountries() method in constructor or ngOnInit(). getAllCountries() is a method to fill the data of countries to dropdown list
getAllCountries() {
this.getHttp().get(this.url)
.map( (response) => {
this.countries = response;
console.log(response); // To check countries is coming or not!
})
}

Related

How to get multiple dynamic drop-down option values in one single list in Angular 7

I am creating a dynamic multiple dropdown in angualar 8. I am receiving list of list from backend and I am running through the list of list to generate multiple dynamic dropdown. Now I need to send selected option values from all the dropdown to backend again in Angular 8. I am unable to send all the value.
I am getting list in this format from which I am looping through to generate dynamic drop-down
cat_dropdown = [['A','B','C'],['1','2','3']]
Based on above list my html code generate two drop-downs one with options A,B,C and another with 1,2,3.
My HTML Code:
<form (ngSubmit)="segmentSelection()" #ff="ngForm">
<div id="userSelection" ngModelGroup="userData" #userData="ngModelGroup">
<div *ngFor="let first of cat_dropdown">
<mat-form-field>
<mat-label>Choose Segment Key</mat-label>
<mat-select id="selectme" name="segmentKey">
<mat-option *ngFor="let segment of first" [value]="segment">
{{segment}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
</form>
My component.ts code:
import { NgForm } from '#angular/forms';
export class myComponent implements OnInit {
#ViewChild("ff", { static: true }) segmentData: NgForm;
plotselection = {
segmentKey: []
}
segmentSelection(){
this.plotselection.segmentKey = this.segmentData.value.userData.segmentKey;
fetch("http://localhost:5000/data-decomposition", {
method: "POST",
headers: {
"Content-Type": "application/json"
},body: JSON.stringify({
segmentKey: this.segmentData.value.userData.segmentKey,
})
}).then(res => res.json()).then(myjson => {
console.log(myjson)
})
}
Now in my .ts component I have a dictionary name "plotselection" where I have key name 'segmentKey' which I defined as empty list.
As I have 2 dropdown in frontend so thought that i will receive two values from frontend and I will send those as a list to backend. When I select option from both the dropdowns for example from 1st dropdown I choose 'B' and from 2nd '3' and submit my selection, then when I console log the response I could only see the value '3' in my list not 'B' and '3' together. How can I have both the value to the list.
Thank you, and looking for your suggestion...
For my easiness I have used Select control instead of mat-select control.
In the form I have given specific name by appending the index to control while looping.
Html
<div *ngFor="let first of cat_dropdown; let num = index">
<div>
<Label>Choose Segment Key</Label>
<Select id="selectme{{num}}" [value]="segment" name="segmentKey{{num}}" (change)="ChangeCall($event.target)">
<option *ngFor="let segment of first" >
{{segment}}
</option>
</Select>
</div>
</div>
So that there are two controls with respective selected values.
There is also alternate solution is use to Change event on the Select Control.

How to set the first item in a select drop down using ngFor in Angular

I have this drop down below and it has all the countries in it, but doesn't display the first value ('United States'). How can I get the first item to be the selected one?
Is it possible to have a conditional statement that sets 'selected' if index = 0? I know two bindings aren't possible, but I'm looking at other alternatives.
<div class="form-group">
<select id="country" class="form-control" formControlName="countryList">
<option *ngFor="let country of countryList;" value={{country}}>
{{country}}
</option>
</select>
</div>
and below is what I see in the page. No item is initially selected. It's blank until I select something!
Update - I'm trying this below, but it doesn't seem to work either.
[value]="country"
[selected]="country == 'United States' ? true : null"
CountryList looks like this
export class Countries {
countryList: string[] = ['United States', 'Afghanistan', 'Albania'];
CountryList() {
return this.countryList;
}
}
// to initialize it, in my component I do this
countryList: string[] = new Countries().countryList;
Assign initial value to the formControl which you want from the countryList.
ex:-
controlModel.controls['countryList'].setValue('United States');

Nothing selected in Select by default - how to fix that?

I'm using Angular 5 and I have a simple Select:
<select class="ui fluid dropdown" formControlName="device">
<option *ngFor="let device of getSenderDevices()" [ngValue]="device">{{device.Name}}</option>
</select>
My problem is the fact that by default nothing is selected, but I'd like the first option to be selected. I saw many threads like this, the solution that I thought would work, does not:
<select class="ui fluid dropdown" formControlName="device">
<option *ngFor="let device of getDevices(); let i = index" [ngValue]="device" [selected]="i==0">{{device.Name}}</option>
</select>
I also found some advices to use compareWith directive - but I wasn't able to understand how it works.
Maybe the problem is caused by getDevices(), which returns data with some delay, because the data is fetched from external server. In the beginning select has to be empty, because the data is not ready yet. When it arrives however, I'd like the select to show that by auto-selecting first option.
Not use a function getDevices() and not use [selected] in .html
//I imagine you have a serviceData that return an observable
export class DataService {
constructor(private httpClient HttpClient) {}
public getDevices():Observable<any>
{
return this.httpClient.get("....");
}
}
constructor(private fb:FormBuilder,private myservice:ServiceData){}
ngOnInit()
{
this.myService.getDevices().subscribe(res=>{
this.devices=res;
this.createForm();
})
//If getDevices() simple return an array, not from service
// this.devices=getServices();
// this.createForm();
}
createForm()
{
this.myForm=this.fb.group({device:this.device[0]})
}
<form [formGroup]="myForm">
<select class="ui fluid dropdown" formControlName="device">
<!--NOT use [selected], when "device" get the value, the select show the value-->
<!--I use the variables "devices"--->
<option *ngFor="let device of devices; let i = index"
[ngValue]="device">{{device.Name}}</option>
</select>
</form>

Load large data in select tag in Angular 4

I have a select tag with thousands of options (names of cities), which the user can choose between as birth city, and is given by a service.
service file
getAllCities () {
return this.httpClient.get<City[]>(this.API_URL + 'cities');
}
In html component file:
<select
class="form-control"
id="city"
name="city"
ngModel
>
<option disabled selected value=""> Select city</option>
<option *ngFor="let elt of cities" [ngValue]="elt.code_city">
{{ elt.city_name }}
</option>
</select>
In component.ts file
getCities(){
this.shareService.getAllCities()
.subscribe(
(response: Array<City>) => {
console.log(response);
this.cities = response;
},
(error) => console.log('Error getting cities: ' + error)
);
}
The problem is that my application block? and does not load the cities, have you any idea how I can do that in angular 4 (which method I must take to prevent this behavior)
thanks
I would recommend to use AutoComplete input for such cases.
You can use one provided by NgPrime for Angular applications.
This is easy to use.
https://www.primefaces.org/primeng/#/autocomplete
Limit your data binding to DOM. Binding too much data to single DOM may block your Application and your user may have to scroll too much to search his city. Use select with search(ng-select) and use limitTo pipe for limited data binding.

Setting selected option of select control in an Angular 2 model-driven form

I have researched many similar existing answers on SO and elsewhere, but just can't find the solution to this.
I'm using the model-driven approach in Angular 2 to build my form, which is both an add and edit form. When in edit mode, the values are populated with data retrieved from a service: this aspect is all fine because the simple text inputs all bind correctly.
One of the properties is 'Country' and this is an object as follows:
export class Country {id: number; name: string;}
I want to bind this to a select control which will have the list of countries available, and the one from the model populated when the form loads. I want the value of the binding to be the country object, not just the id.
Here's the html of the select control:
<select class="form-control" id="country" formControlName="country">
<option value="default">--Select a country--</option>
<option *ngFor="let c of countries" [value]="c">{{c.name}} </option>
</select>
And here is where i try to to populate the value from the component class:
(<FormControl>this.personForm.controls['country'])
.setValue(this.person.country, { onlySelf: true });
But there is no selected option when the page loads, even though the console confirms that this.person.country exists and is populated with the correct object.
I can get it working with ids: changing to [value]="c.id" in the view and appending .id in the class, and then it works in that the right option is selected. The problem is that the select no longer emits an object for the country property, just the id. I tried changing [value] to [ngValue] and get the same result. I even added [ngModel]="country" to the select element and that didn't help either.
I'd be grateful for any help.
The issue is most likely that this.person.country is not the same country as in your countries array.
If we want to make them the same we can either explicitly subscribe to the valueChanges of the select control or bind [(ngModel)] to person.country:
subscribe to changes
code
this.countryForm.controls['country'].valueChanges.subscribe(country =>
this.person.country = country;
);
// initialize by finding the correct country object (this will overwrite the person's country object)
this.countryForm.controls['country'].setValue(countries.filter(c => c.id === person.country.id));
template
ngModel bind
We still have to make the objects match (compare strategy that Angular 2 uses which is really what JS uses)
code
this.person.country = this.countries.filter(c => c.id === this.person.country.id)[0];
template
<select class="form-control" id="country" formControlName="country" [(ngModel)]="person.country">
<option value="default">--Select a country--</option>
<option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>
ngModel Plunker: http://plnkr.co/edit/UIS2V5rKh77n4JsjZtii?p=preview
subscription Plunker: http://plnkr.co/edit/yyZ6ol1NPD77nyuzwS2t?p=info