角度ngFor乱序

时间:2018-12-13 07:47:55

标签: arrays angular

我有几个月的时间。由于某种原因,角度for循环不遵循数组的顺序。 How can that be fixed

@Component({
  selector: 'my-app',
  template: `<div *ngFor="let item of collection | keyvalue; index as i">{{item | json}}</div>`,
})
export class AppComponent  {
  collection : {key : any, value : any}[] = [];

  constructor(){
    let i = 0;
    for(let month of moment().locale('en-US').localeData().monthsShort()){
       i++;
      this.collection.push({key : i,value : month});
    }
  }

https://stackblitz.com/edit/angular-i25npn?file=src%2Fapp%2Fapp.component.ts

2 个答案:

答案 0 :(得分:3)

根据docs<div *ngFor="let item of collection">{{item | json}}</div> 的定义。

  

输出数组将按键排序。默认情况下比较器   将会是Unicode点值...

因此,默认情况下,您的键(字符串)是有序的。

keyvalue中删除管道| keyvalue; index as i

答案 1 :(得分:1)

要遵循该命令,请替换:

<?php
namespace Facebook\WebDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

require_once('vendor/autoload.php');

$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::chrome();
$driver = RemoteWebDriver::create($host, $capabilities, 5000);

$driver->get("https://healofy.com/"); 

$driver->findElement(WebDriverBy::xpath('//label[@for="Baby_1_2_years"]'))->click();
//$driver->quit();

?>

作者:

<div *ngFor="let item of collection | keyvalue; index as i">{{item | json}}</div>