基于datepicker定义自己的angular时间组件的示例
作者:阿踏
这篇文章主要介绍了基于datepicker定义自己的angular时间组件,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
基于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 就可以在任意模块引入然后使用,减少代码的使用,方便维护
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- AngularJS 日期格式化详解
 - 详解Angularjs在控制器(controller.js)中使用过滤器($filter)格式化日期/时间实例
 - Angularjs中使用layDate日期控件示例
 - Angular指令封装jQuery日期时间插件datetimepicker实现双向绑定示例
 - Angularjs验证用户输入的字符串是否为日期时间
 - Angular4.0中引入laydate.js日期插件的方法教程
 - angularjs封装bootstrap时间插件datetimepicker
 - angularjs实现时间轴效果的示例代码
 - bootstrap timepicker在angular中取值并转化为时间戳
 - AngularJS日期格式化常见操作实例分析
 
