Issue
I have a JSON object which has all data of input fields like below. I am creating UI by binding these JSON value.
inputs = [{"name": "Name", "type": "text", "value": null},
{"name": "City", "type": "select", "options": this.cityArr, "value": null}]
I am calling API to get values of this.cityArr
like below:
getCityList(){
this.dataService.getCityList().subscribe((data: any) => {
this.cityArr = data.city;
console.log("city Arr" + this.cityArr);
});}
I got array of city in console but I can not get this list in "options": this.cityArr
as I initialize cityArr like cityArr:any = [];
So how I can override global initialized variable with local values.
I have call getCityList()
in ngOnInit()
but it doesn’t affect any change. Thanks in advance.
Below is the StackBlitz link
https://stackblitz.com/edit/angular-jez775?file=src%2Fapp%2F
Solution
I was able to fix this via this typescript :-
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
cityArr: any = [];
inputs = [
{ name: "Name", type: "text", value: null },
{ name: "City", type: "select", options: this.cityArr, value: null }
];
ngOnInit() {
this.getCityList();
}
getCityList() {
this.cityArr = ["Mumbai", "Benglore", "Chennai"];
this.inputs[1].options = this.cityArr;
}
}
and template :-
<div *ngFor="let input of inputs">
<input *ngIf="input.type == 'text'" type={{input.type}} value={{input.value}}/>
<select *ngIf="input.type == 'select'">
<option *ngFor="let option of input?.options">{{option}}</option>
</select>
</div>
Working Stackblitz :- https://stackblitz.com/edit/angular-hpampb?file=src/app/app.component.ts