当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 基于datepicker定义自己的angular时间组件的示例

基于datepicker定义自己的angular时间组件的示例

2018年04月03日  | 移动技术网IT编程  | 我要评论

基于datepicker定义自己的angular时间组件,分享给大家。

首先是引入相应的文件jquery和datepicker,如下

 "styles": [
   "styles.less",
   "./assets/lib/datetimepicker/datetimepicker.css"
  ],
  "scripts": [
   "assets/lib/jquery/jquery.min.js",
   "./assets/lib/datetimepicker/datetimepicker.js",
  ],

然后是ts文件

import { component, eventemitter, oninit, afterviewinit, elementref, input, output } from '@angular/core';
import { controlvalueaccessor, ngcontrol } from '@angular/forms';

declare var $: any;

@component({
 selector: 'my-datepicker',
 template: '<input [name]="name" [disabled]="disabled" class="ant-input" [value]="value">'
})

export class mydatepickercomponent implements oninit, afterviewinit, controlvalueaccessor {
 constructor(
  private _element: elementref,
  public _control: ngcontrol
 ) {
  if (this._control) {
   this._control.valueaccessor = this;
  }
 }

 @input()
 name:string;

 @input()
 disabled:string;

 @input()
 options:object = {};

 @input('ngmodel')
 value: string;

 @output() onchoose = new eventemitter<any>();
 
 defaults: object;

 _onchange = (value: any) => {};

 writevalue(value: string) {
  if (value) {
   this.value = value;
  }
 }

 registeronchange(fn: (value: any) => void) {
  this._onchange = fn;
 }

 registerontouched(fn: any) {

 }

 ngoninit() {
  if (this.value == undefined) {
   this.value = '';
  }

  let _this = this;
  this.defaults = {
       format: 'yyyy-mm-dd',
       istoday:true,
       choosefun: function(ele, data){
        _this._choose(data);
       },
       clearfun: function(){
        _this._clear();
       },
       closefun: function() {
        _this._close();
       }
      };
 }

 ngafterviewinit() {
  let options = $.extend({}, this.defaults, this.options);

  $(this._element.nativeelement).find('input').jedate(options)
   .on('click', function(e) {
    e.stoppropagation();

    $(this).addclass('focus').blur();
   });
 }

 private _choose(value: string) {
  this._onchange(value);

  this.onchoose.emit(value); // 选中事件
 }

 private _clear() {
  this._onchange('');

  this.onchoose.emit(''); // 选中事件
 }

 private _close() {
  $(this._element.nativeelement).find('input').removeclass('focus');
 }
}

最后是调用,option里面定义自己的时间格式

复制代码 代码如下:

 <my-datepicker  name="jssj" [(ngmodel)]="search.jssj" [options]="{format:'yyyy-mm-dd hh:mm:ss'}"></my-datepicker>

总结:通过这个组件,我们只需要调用my-datepicker 就可以在任意模块引入然后使用,减少代码的使用,方便维护

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网