Angular 2 + 折騰記 :(6) 動手實現只有年月的小元件

CRPER發表於2017-03-30

前言

這個元件實現並不是很複雜,我會盡量註釋;
這貨誕生的理由就是專案剛好有一個地方必須只能選擇年月,而githubng2+日期元件都涉及到年月日或時分秒;
效果用gifcam錄製的,色彩有些失真,將就吧。。動手動手出真理


效果圖


實現思路

  1. 月份只有十二個,只要把個位數做好補位就好
  2. 年份的生成是可控的(傳參),當前年份往前推幾年和往後推幾年構成;
  3. 資料遍歷結構很簡單
{
    date:2017, // 月份是字串,年份是數字
    active:false,
    type:'year' // 月份是'month'
}複製程式碼

頁面樣式就自行折騰啦,我這裡只是用了最直白粗暴的下拉滑動

在ng4寫的。動畫模組需要單獨引入,可以看我的其他文章有介紹


實現程式碼

  • html
<div class="only-year-month-select">
  <div class="select" (click)="isExpand = !isExpand">
    <input type="text" [placeholder]="placeholder" class="form-control" [(ngModel)]="selected" [disabled]="true">
  </div>
  <div class="list-menu" *ngIf="isExpand" [@fadeIn]="true">
    <div class="sub-list1">
      <p class="title">年份</p>
      <ul class="year-wrap">
        <li *ngFor="let i of selectYearRange;let index = index" [class.active]="i.active" (click)="actValue(selectYearRange,index)"
          (dblclick)="emitResult(i)">{{i.date}}</li>
      </ul>
    </div>
    <div class="sub-list2">
      <p class="title">月份</p>
      <ul class="month-wrap">
        <li *ngFor="let i of selectMonthRange;let index = index" [class.active]="i.active" (click)="actValue(selectMonthRange,index)"
          (dblclick)="emitResult(i)">{{i.date}}</li>
      </ul>
    </div>
  </div>
</div>複製程式碼
  • components
import { Component, OnInit, Input, Output, EventEmitter, HostListener, ElementRef } from '@angular/core';

// 動畫
import { fadeIn } from '../../animation/fadeIn';

@Component({
  selector: 'app-only-year-month-select',
  templateUrl: './only-year-month-select.component.html',
  styleUrls: ['./only-year-month-select.component.scss'],
  animations: [fadeIn]
})
export class OnlyYearMonthSelectComponent implements OnInit {
  @Input() public placeholder: string;
  @Input() public range: any;
  @Output() public result = new EventEmitter();
  public isExpand = false;
  public selectYear: any;
  public selectMonth: any;
  public selectYearRange: Array<any> = [];
  public selectMonthRange: Array<any> = [];
  public selected: any;
  constructor(
    private _el: ElementRef
  ) { }

  ngOnInit() {
    this.getCurrentDate();
  }

  // 獲取當前的年月
  getCurrentDate(): void {
    const TODAY = new Date();
    this.selectYear = TODAY.getFullYear();
    this.selectMonth = TODAY.getMonth() < 9 ? '0' + (TODAY.getMonth() + 1) : String(TODAY.getMonth() + 1);
    this.selectYearRange.push(
      {
        date: this.selectYear,
        active: true,
        type: 'year'
      }
    );
    this.selectMonthRange.push(
      {
        date: this.selectMonth,
        active: true,
        type: 'month'
      }
    );
    this.selectYearRange = this.getRangeYear(this.selectYear, this.range.before, this.range.after);
    this.selectMonthRange = this.getRangeMonth(this.selectMonth);
    console.log(this.selectYearRange, this.selectMonthRange);
  }

  // 需要生成的日期範圍
  getRangeYear(year: number, before: number = 5, after: number = 10): any {
    // console.log(year, before, after);

    let _beforeYear = year;
    let _afterYear = year;

    for (let i = 0; i < before; i++) {
      this.selectYearRange.unshift(
        {
          date: --_beforeYear,
          active: false,
          type: 'year'
        }
      );
    }
    for (let j = 0; j < after; j++) {
      this.selectYearRange.push(
        {
          date: ++_afterYear,
          active: false,
          type: 'year'
        }
      );
    }
    return this.selectYearRange;
  }

  // 月份範圍
  getRangeMonth(month): any {
    for (let i = 0; i < 12; i++) {
      const temp = i < 9 ? '0' + (i + 1) : '' + (i + 1);
      if (month !== temp) {
        this.selectMonthRange.push(
          {
            date: temp,
            active: false,
            type: 'month'
          });
      }
    }
    this.selectMonthRange.sort(this.compare('date'));
    return this.selectMonthRange;
  }

  // 陣列物件排序
  compare(property) {
    return function (a, b) {
      const value1 = a[property];
      const value2 = b[property];
      return value1 - value2;
    };
  }

  // 年份或者月份選擇
  actValue(list: any, index: number) {

    list.forEach((v, i) => {
      if (i === index) {
        v.active = true;
        if (v.type === 'year') {
          console.log(v.date);
          this.selectYear = v.date;
        }
        if (v.type === 'month') {
          console.log(v.date);
          this.selectMonth = v.date;
        }

      } else {
        v.active = false;
      }
    });
    this.emitResult();
  }



  // 獲取結果集
  emitResult(e?: any) {
    if (e) { // 雙擊則關閉彈出
      this.isExpand = false;
    }
    this.selected = this.selectYear + '-' + this.selectMonth;
    this.result.emit(this.selected);

  }


  // 監聽全域性點選事件
  @HostListener('document:click', ['$event.target'])
  public onClick(targetElement) {
    const clickedInside = this._el.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this.isExpand = false;
      this.emitResult();
    }

  }
}複製程式碼
  • fadeIn.ts
// 動畫的效果很簡單,就是把css3的效果用js來實現,具體的效果就是漸現
// 放在突然出來一塊區域的地方,觸發看起來會比較順眼,有個過渡

import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';
//transition(':enter', [ ... ]); // void => *
//transition(':leave', [ ... ]); // * => void
export const fadeIn = trigger('fadeIn', [
  state('in', style({ display: 'none' })),
  transition('void => *', [
    animate(200, keyframes([
      style({ height: '0', opacity: 0, offset: 0 }),
      style({ height: '*', opacity: 1, offset: 1 })
    ]))
  ]),
  transition('* => void', [
    animate(200, keyframes([
      style({ height: '*', opacity: 1, offset: 0 }),
      style({ height: '0', opacity: 0, offset: 1 })
    ]))
  ]),
]);

// 200 是過渡時間,毫秒
// offset相當於 css3 中keyframes的百分比,,控制動畫的進度的。。0 -> 1 就相當於 0% -> 100%複製程式碼
  • 封裝成一個模組給其他使用
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { OnlyYearMonthSelectComponent } from './only-year-month-select.component';

@NgModule({
  imports: [
    CommonModule, // 用用到一些內建的指令必須依賴這個,比如*ngIF, *ngFor
    FormsModule // 有用到表單元素必須引入這貨
  ],
  declarations: [OnlyYearMonthSelectComponent], // 宣告年月元件
  exports: [OnlyYearMonthSelectComponent] // 匯出年月元件
})
export class OnlyYearMonthSelectModule { }複製程式碼

元件使用

溫馨提示:

  • 若不是以模組的方式到處,只要在使用的模組引入元件宣告下就能使用
  • 反之則需要引入這個模組,方可使用

區域性程式碼

  • module
// 在要使用的模組中引入
// 公用元件
import { MitEhartsModule } from '../../../widgets/mit-echarts/mit-echarts.module';
import { MitDataTableModule } from '../../../widgets/mit-data-table/mit-data-table.module';
import { MitLoadingModule } from '../../../widgets/mit-loading/mit-loading.module';
import { OnlyYearMonthSelectModule } from '../../../share/only-year-month-select/only-year-month-select.module';
import { DepartmentSelectModule } from '../../../share/department-select/department-select.module';
const mitModule = [
  MitEhartsModule,
  MitDataTableModule,
  MitLoadingModule,
  DepartmentSelectModule,
  OnlyYearMonthSelectModule
]
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    NgbDatepickerModule,
    ...mitModule,
    DailyCarRoutes
  ],
  providers: [DailyCarService],
  declarations: [...page]
}複製程式碼
  • html
<div class="form-group condition-wrapper">
  <label class="form-control-label">月份</label>
  <app-only-year-month-select class="form-control" [placeholder]="'yyyy-mm'" (result)="Time = $event" [range]="{before:5,after:10}"></app-only-year-month-select>
</div>複製程式碼

總結

文章有錯誤之處亦或者有更好寫法和建議的請留言指出,會及時改進和跟進...;
下一篇文章說下指令或者動畫相關的。。。。整理下思路

相關文章