如何使用 angular 6 更改数组的索引?

How can I change the index of array using angular 6?

我的打字稿中有这个数组。我正在使用 angular 6.

formats: any = ['Years/Months/Days', 'Years/Months/Week', 'Months/Days', 'Week/Days', 'Week/Half Days', 'Week/4 Hours', 'Week/Hours', 'Days/Hours/30Min', 'Days/Hours/15Min'];

这是我的 html 代码。

<select class="form-control" formControlName="format">
    <option [ngValue]="null">{{'Select Type' | translate}}</option>
    <option *ngFor="let format of formats" [ngValue]="format">{{format}}</option>
</select>

我想借助下一个和上一个按钮更改下拉值。

我建议你有一个变量来存储所选选项的索引并将其初始化为零,每次更改所选值时更新索引。

然后您可以为下一个和上一个创建两个按钮,并将点击事件映射到两个按钮

.ts 文件和函数可能看起来像这样

selectedindex:any = 0;

changed(event : Event):any{
 console.log(event)
if( event.target){
console.log( this.formats.indexOf(this.yourformobject.controls['format'].value))
this.selectedindex = this.formats.indexOf(this.yourformobject.controls['format'].value;
}
}
next():any{
 if(this.selectedindex < this.formats.length-1){
this.selectedindex++;
this.yourformobject.controls['format'].setValue(this.formats[this.selectedindex]);

 }
}

previous():any{
if(this.selectedindex>0){
this.selectedindex--;
this.yourformobject.controls['format'].setValue(this.formats[this.selectedindex]);

}
}

Html 看起来像这样

<form [formGroup]="yourformobject">
  <select class="form-control" formControlName="format" (click)="changed($event)">
    <option [ngValue]="null">Select Type</option>
    <option *ngFor="let format of formats" [ngValue]="format">{{format}}</option>
</select>
<button (click)="next()">next</button>
<button (click)="previous()">previous</button>
</form>