[Fixed] How to override global variable with values inside function in angular


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:

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



I was able to fix this via this typescript :-

import { Component } from "@angular/core";

  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() {

  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>


Working Stackblitz :- https://stackblitz.com/edit/angular-hpampb?file=src/app/app.component.ts

Leave a Reply

(*) Required, Your email will not be published