单击角度2

时间:2017-06-11 06:21:46

标签: angular

我想在下拉列表中显示当前年份作为默认日期,当点击上一页按钮时,它应该将年份减一,并且它应该影响Angular 2中下拉列表中选定的年份值

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <h2>Select demo</h2>
    <a (click)="changeYear()">Prev</a>
    <select [(ngModel)]="selectedyear" (ngModelChange)="onChange($event)" >
      <option *ngFor="let c of year" [ngValue]="c"> {{c}} </option>
    </select>
  `
})
class App {
  year  = ['2016','2015','2014'];

  selectedyear ;

  onChange(year) {
    alert(year);
    this.selectedyear = year;
  }

  changeYear(){
    this.selectedyear = this.selectedyear -1;
    this.onChange(this.selectedyear);

  }
}


@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

1 个答案:

答案 0 :(得分:0)

问题是当您在2014年之后点击上一个按钮时,它将是2013年,您在阵列年内没有它。

所以每当你减少检查元素是否存在于数组内部时,如果没有在数组内部推送。

 changeYear(){
    this.selectedyear = this.selectedyear -1;
    this.year.push(this.selectedyear); 
  }

DEMO