显示动态创建的数组TypeScript,Angular 2+

时间:2018-10-08 12:24:57

标签: angular typescript

我正在创建一个动态生成的数组,并且希望该数组在我的HTML上显示,但是我缺少一些我无法弄清楚的东西
    app-component.ts

StateClick(stateClicked,index) {

// StateName is an array from which I will get the index of my state.
var indexCollector = this.StateName.indexOf(stateClicked);

// Creating Array Dynamically
window['asd'+index] = new Array();

// CityName array from which i will get an array present at that index
this.asd0 = this.CityName[indexCollector];

// Value is visible in console
console.log(this.asd0);
}

我的数组:随机数据

StateName: any[] = ['Andhra Pradesh', 'Jharkhand', 'Kerala'];
CityName: any[] = [

[     'Adoni',
      'Amaravati',
      'Anantapur',
      'Tadepalligudem',
      'Tadipatri',
      'Tenali',
      'Tirupati',
      'Kadapa',
      'Kakinada',
      'Kurnool'
    ],
    ['Patna',
      'Gaya',
      'Muzaffarpur',
      'Darbhanga',
      'Bhagalpur',
      'Nalanda',
      'Tirupati',
      'Begusarai'
    ],
    ['Jamnagar',
      'Ankleshwar',
      'morbi',
      'Valsad',
      'Bhavnagar'
    ],
];

app-component.html

  <div *ngFor="let userCheckedValueDetails of userCheckedValue ; let idx = index">
 <select>
 <option [selected]=true>Select City</option>

 // This is where I trying to display my dynamically generated array but not able
   // to fetch it asd+idx

    <option value="{{StoringCityArray}}" *ngFor="let StoringCityArray of asd+idx">
        {{StoringCityArray}}
    </option>
 </select>
 </div>

如我的代码所示,我正在尝试获取动态生成的数组,但我无法读取它

1 个答案:

答案 0 :(得分:0)

您的数组不是一维的,因此您需要展平数组并运行* ngFor或运行2个嵌套的* ngFor(不推荐)

<option selected="true">Select City</option>
<option value="{{StoringCityArray}}" *ngFor="let StoringCityArray of asd_idx[0]">
    {{StoringCityArray}}
</option>

  • 您忘了在第一次选择时添加过时的内容,并且由于它是静态的,因此不需要[]

  • 我不建议将+号用作变量名。

  • 像这样初始化数组(不要使用窗口)

    状态:any [] = [];

  • 将新状态推入数组,如下所示:

    for(让i = 0; i