angular2--使用iosSelect實現選擇出生年月日的三級聯動

實現效果如下所示:

官方文檔:http://zhoushengfe.com/iosselect/website/index.html

1、使用npm

npm install iosselect

2、下載相關文件
下載文件到項目目錄中,在angular.json中引入css和js文件,路徑按需調整。
鏈接:https://pan.baidu.com/s/1GP0qLuZS8_36QT5RkZ0ptQ
提取碼:d60g
在這裏插入圖片描述

3、在typings.d.ts定義變量

declare var IosSelect: any ;

4、html

點擊“選擇生日”時,調用核心方法chooseBirthday,彈起三級聯動選擇框。
<div class="r-input" (click)="chooseBirthday()" id='birthday' data-year-code='birthdayYearId' data-month-code='birthdayMonthId'  data-day-code='birthdayDayId' >
	<span class="r-left">選擇生日</span>
	<span class="r-right">{{birthday||'僅自己可見 >'}}</span>
</div>

5、ts
(1) 定義變量

birthday: any; //出生日期
birthdayYearId: string; //出生年份ID
birthdayMonthId: string; //出生月份ID
birthdayDayId: string; //出生日ID

//出生年月數據
birthdayYearData: any = [];
birthdayMonthData = [];
birthdayDayData = [];

(2) 初始化三級聯動的數據:

年:1949~2019(當年)
月:01-12(當月份<10時,在數字前面添加0)
日:01-31(當天數<10時,在數字前面添加0)
//獲取--年月日
getYear() {
	let sum = 1949;
	let index = 0;
	let dt = new Date();
	let ndt = dt.getFullYear() ;  //獲取當年年份
	let num = ndt - sum;

	for(let i = 0; i < num; i++) {
		sum = sum + 1;
		index = index + 1;
		this.birthdayYearData.push({
			id: index,
			value: sum
		})
	}
}

getMonth() {
	let sum = 0;
	let index = 0;
	for(let i = 0; i < 12; i++) {
		sum = sum + 1;
		index = index + 1;
		if(sum < 10) {
			this.birthdayMonthData.push({
				id: index,
				value: '0' + sum
			})
			
		} else {
			this.birthdayMonthData.push({
				id: index,
				value: sum
			})
		}
	}
}

getDay() {
	let sum = 0;
	let index = 0;
	for(let i = 0; i < 31; i++) {
		sum = sum + 1;
		index = index + 1;
		if(sum < 10) {
			this.birthdayDayData.push({
				id: index,
				value: '0' + sum
			})
		} else {
			this.birthdayDayData.push({
				id: index,
				value:sum
			})
		}
	}
}

(3) 核心方法:

chooseBirthday() {
	var that = this;
	that.getYear();
	that.getMonth();
	that.getDay();
	var select = new IosSelect(3, [that.birthdayYearData, that.birthdayMonthData, that.birthdayDayData], {
		title: '',
		itemHeight: 35,
		oneLevelId: that.birthdayYearId,
		twoLevelId: that.birthdayMonthId,
		threeLevelId: that.birthdayDayId,
		callback: function(selectOneObj, selectTwoObj, selectThreeObj) {
			that.birthdayYearId = selectOneObj.id;
			that.birthdayMonthId = selectTwoObj.id;
			that.birthdayDayId = selectThreeObj.id;
			that.birthday = selectOneObj.value + '-' + selectTwoObj.value + '-' + selectThreeObj.value;
		}
	});
}

6、css

.r-input{
	display: flex;
	justify-content: space-between;
	padding: 8px 0;
    margin-top: 55px;
	border-bottom: 1px solid #f2f2f2;
}

.r-left{
	font-size: 17px;
	color: #a8a8a8;
}

.r-right{
	color: #a1a1a1;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章